Redux Toolkit是為了解決Redux關於需要太多重複相同模式的樣板代碼和複雜的store configure等等缺點,以更簡單的方式實現Redux作為全局狀態管理器。今天先介紹基本操作流程。
npm install @reduxjs/toolkit react-redux
首先建立一個Store.js 檔,然後導入configureStore,再建立store物件
store.js
import {configureStore} from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {
}
})
index.js
import {store} from './ store';
import {Provider} from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Slice是將redux狀態物件拆分成多個狀態切片,切片實際上是應用程序中reducer和action的集合, 例如我們今天要做一個計數器,其中可能有一個有增量切片和減量切片。設置如下:
4-1. import {createSlice} from "@reduxjs/toolkit";
4-2 建立狀態初始值
4-3. createSlice()函數有三個參數設定:
第一個name
第二個是初始狀態initialState
第三個是reducer,在這裡命名所有不同的action。
4-4 export action和reducer
import {createSlice} from "@reduxjs/toolkit";
const initialState = {
count : 0
}
export const counterSlice = createSlice({
name:'counter',
initialState,
reducers:{
increment:(state)=>{
state.count += 1;
},
decrement:(state)=>{
state.count -= 1;
},
}
});
export const {increment,decrement} = counterSlice.actions
export default counterSlice.reducer;
將countReducer添加到store中,將其他的切片導入同一store中,它可以通過我們放在store提供給整個應用程序
import {configureStore} from "@reduxjs/toolkit";
import counterReducer from './counter/conunterSlice';
export const store = configureStore({
reducer: {
counter:counterReducer,
}
})
useSelector(),接收應用程式中的狀態值。
useDispatch(),調用我們在reducer中設定的action。
import { useSelector,useDispatch } from 'react-redux';
import { increment,decrement } from './conunterSlice';
const Counter = () => {
const count = useSelector((state) =>state.counter.count);
const dispatch = useDispatch();
return (
<div className='container'>
<div className="app">
<h1>{count}</h1>
</div>
<div>
<button onClick = {()=>dispatch(increment())}>+</button>
<button onClick = {()=>dispatch(decrement())}>-</button>
</div>
</div>
)
}
export default Counter