DEV Community

Teerasak Vichadee
Teerasak Vichadee

Posted on

บันทึกความเข้าใจ Redux Toolkit

ใครๆก็รู้ว่า redux มี store, reducer และ action

  • store มีหน้าที่ dispatch action
  • reducer เก็บ logic ที่จะเปลี่ยนแปลง state ที่เราสนใจ ตามประเภทของ action ที่กำหนด โดยอ้างอิงกับ state
  • action คือ constant ที่เรากำหนดสำหรับ component นั้นๆ

ตัวอย่างการเขียน redux แบบบ้านๆ

function counter(state, action) {
  if (typeof state === 'undefined') {
    return 0
  }

  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

var store = Redux.createStore(counter)

document.getElementById('increment').addEventListener('click', function() {
  store.dispatch({ type: 'INCREMENT' })
  // state = 1
})
Enter fullscreen mode Exit fullscreen mode

จากตัวอย่าง

  • counter() คือ reducer ที่คอยรับ action
  • action มี INCREMENT และ DECREMENT
  • เมื่อสั่ง dispatch({ type: INCREMENT }) เลยทำให้ state มีค่าเท่ากับ 1

จากตัวอย่างข้างบน จะเห็นว่ามันอาจจะเกิดปัญหาบางอย่างในการเขียน เช่น ใช้ action ผิด, ไม่รู้ว่า action มีอะไรบ้าง, เขียนเยอะ ฯลฯ

ณ จุดนี้ เราสามารถใช้ redux-toolkit แก้ปัญหาได้ ดังนี้

export const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: state => state + 1,
    decrement: state => state - 1
  }
})

const store = configureStore({
  reducer: counterSlice.reducer
})

document.getElementById('increment').addEventListener('click', () => {
  store.dispatch(counterSlice.actions.increment())
  // state = 1
})
Enter fullscreen mode Exit fullscreen mode

จากตัวอย่างของการใช้ createSlice จะเห็นว่า แค่ import counterSlice มาสร้าง store
เราก็สามารถใช้ action ได้จาก counterSlice.actions ซึ่งก็จะ list มาเฉพาะตัวที่ระบุไว้ ไม่ต้องเดาหรือไปดูใน code

น่าเอาไปใช้ในโปรเจคอื่นๆเนอะ ลดบรรทัดลงไปเยอะ

Note

  1. เรียบเรียงจาก: Basic Redux Toolkit Tutorial
  2. Redux Toolkit github, npm

Top comments (2)

Collapse
 
sutthiej profile image
sutthiej

ดูจากแหล่งอื่น อธิบายไม่รู้เรื่องเลย ดูที่นี่ กระจ่างเลย

Collapse
 
ilumin profile image
Teerasak Vichadee

ขอบคุณมากครับ :D