Redux Toolkit 筆記

建立模板

1
npx create-react-app my-app --template redux

環境建立流程

  1. 先使用 configureStore 新增 store,store 裡面新增 reducer。(src/app/store.js)
1
2
3
4
5
6
7
8
import { configureStore } from '@reduxjs/toolkit'
import todoReducer from '../features/todo'

export const store = configureStore({
reducer: {
todoReducer
},
})
  1. 新增 reducer,使用 createSlice 建立 Slice,傳入三個參數。(features/todo.js)
    • 名字
    • 初始化的 state
    • reducers,透過工具,把對應的 action 產生出來。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { createSlice } from '@reduxjs/toolkit'

const initialState = {
todoList: []
}

export const todoSlice = createSlice({
name: 'todo',
initialState,
reducers: {
// 1.state -> 當下的狀態
// 2.action.payload -> 對應的內容
addTodo: (state, action) => {
// payload -> 當下的內容要新增的東西
state.todoList.push(action.payload)
},
addTimestamp: (state) => {
state.todoList.push(Date.now().toString())
}
},
})


export const { addTodo, addTimestamp } = todoSlice.actions
// 最後把 Reducer 裝在 store 裡
export default todoSlice.reducer
  1. useAppSelectoruseAppDispatch 可以用來存取資料。按下 UI 就會發送 dispatch,dispath 裡面就會夾帶 action。(src/App.js)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { useSelector, useDispatch } from 'react-redux'
import { addTodo, addTimestamp } from './features/todo'

// 如何拿到狀態 -> store 給建立好之後,透過 selector 的方式,放在 ui 上面。
// ui 就可以透過 selector,拿到 store。
const todoReducer = useSelector((state) => state.todoReducer)
const todoList = todoReducer.todoList;
const dispatch = useDispatch()
const [text, setText] = useState('');

<NoteInput
type='text'
value={text}
onChange={(e) => setText(e.target.value)
}
/>
{/* 點擊按鈕後,dispatch 出去 */}
<SubmitBtn
onClick={() => {
if (text === '') {
alert('請輸入todo內容');
return;
}
dispatch(addTodo(text));
setText('');
}}
>

Redux Toolkit 筆記
https://phoebeho.com/React/20220601/1083783493/
作者
Phoebe
發布於
2022年6月1日
許可協議