React中使用Redux Toolkit狀態(tài)管理的示例詳解
一、什么是源 Store 和根 Store?
這里只是自己覺(jué)得這樣定義會(huì)更好理解一些,實(shí)際并沒(méi)有這樣的概念
源 Store
源 store 是模塊化的狀態(tài)管理單元,負(fù)責(zé)特定功能的狀態(tài)和操作。使用 createSlice 創(chuàng)建的 slice 就是源 store。
類比:可以想象成一個(gè)專注于特定產(chǎn)品的車間,例如一個(gè)玩具制造車間。它只負(fù)責(zé)制造特定類型的玩具(如計(jì)數(shù)器的狀態(tài)管理),并且有自己的一套操作流程(增、減、重置)。
根 Store
根 store 是整個(gè)應(yīng)用的狀態(tài)管理中心,使用 configureStore 組合多個(gè)源 store。它負(fù)責(zé)將所有的狀態(tài)和邏輯集中起來(lái),提供給整個(gè)應(yīng)用使用。
類比:可以想象成一個(gè)大型工廠,里面有多個(gè)車間(源 store)。有負(fù)責(zé)制造玩具的,有負(fù)責(zé)制造家具的。。。這個(gè)工廠負(fù)責(zé)管理和協(xié)調(diào)各個(gè)車間的生產(chǎn),并且能夠根據(jù)需求調(diào)整生產(chǎn)線(即添加或修改源 store)。

二、創(chuàng)建 Counter Store
2.1 定義源 Store
在一個(gè)新的文件 counterSlice.js 中,我們將創(chuàng)建計(jì)數(shù)器的 slice:
// store/modules/xxx.js
import { createSlice } from '@reduxjs/toolkit';
// 創(chuàng)建一個(gè) slice
const counterSlice = createSlice({
name: 'counter', // 定義 slice 的名稱
initialState: { // 初始化狀態(tài)
count: 0, // 需要被全局維護(hù)的數(shù)據(jù)
},
reducers: { // 定義修改狀態(tài)的方法
increment(state) {
state.count += 1; // 增加計(jì)數(shù)
},
decrement(state) {
state.count -= 1; // 減少計(jì)數(shù)
},
reset(state) {
state.count = 0; // 重置計(jì)數(shù)
},
},
});
// 導(dǎo)出 action 對(duì)象
export const { increment, decrement, reset } = counterSlice.actions;
// 導(dǎo)出 reducer 函數(shù)
export const counterReducer = counterSlice.reducer;在這個(gè)例子中,counterSlice 就是我們的源 store,它初始化了一個(gè) count 狀態(tài),并提供了三個(gè) reducers 來(lái)修改這個(gè)狀態(tài)。
三、組合 Store(根)
在另一個(gè)文件 store.js 中,我們將使用 configureStore 來(lái)組合根 store,并把 counterReducer 傳入:
// store/index.js
import { configureStore } from '@reduxjs/toolkit';
import { counterReducer } from './counterSlice';
// 創(chuàng)建根 store
const store = configureStore({
reducer: {
counter: counterReducer, // 將源 reducer 組合到根 store 中
},
});
export default store;這里,store 就是我們的根 store,它可以容納多個(gè)源 store(在本例中只有 counter),并將它們組合在一起進(jìn)行集中管理。
根store中可以定義多個(gè)源store,這里只示例一個(gè)
四、連接 React 和 Redux
我們目前只是使用了源store中的reducer函數(shù)來(lái)組合根store,還有定義導(dǎo)出的源store中的action對(duì)象并沒(méi)有使用
現(xiàn)在我們已經(jīng)定義了 store,但還需要將其鏈接到我們的 React 應(yīng)用中。我們將使用 react-redux 中的 Provider 組件來(lái)實(shí)現(xiàn)這一點(diǎn)。
4.1 綁定 Store(為組件注入store)
在 index.js 或 App.js 中,我們將 Provider 組件包裹住我們的應(yīng)用:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);4.2 使用 Store 中的數(shù)據(jù)(調(diào)用觸發(fā))
在我們的組件中,使用 useSelector 鉤子來(lái)訪問(wèn) store 中的狀態(tài),并使用 useDispatch 鉤子來(lái)觸發(fā) action。
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, reset } from './counterSlice';
const Counter = () => {
const count = useSelector(state => state.counter.count); // 獲取狀態(tài)
const dispatch = useDispatch(); // 獲取 dispatch 函數(shù)
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
<button onClick={() => dispatch(reset())}>Reset</button>
</div>
);
};
export default Counter;在這個(gè)組件中,我們通過(guò) useSelector 獲取 count 狀態(tài),并通過(guò) useDispatch 觸發(fā) increment、decrement 和 reset 這三個(gè) action。
總結(jié)
通過(guò)以上步驟,我們成功使用 Redux Toolkit 創(chuàng)建了一個(gè)簡(jiǎn)單的計(jì)數(shù)器應(yīng)用。整個(gè)過(guò)程包括:
- 定義源 store(創(chuàng)建 slice)。
- 將源 store 組合到根 store 中。
- 通過(guò)
Provider注入 store 到 React 應(yīng)用中。 - 使用
useSelector和useDispatch連接組件與 store,實(shí)現(xiàn)狀態(tài)管理。
擴(kuò)展:
1.action傳參:
- 對(duì)源store的reducer中的action對(duì)象多傳遞一個(gè)action參數(shù),這個(gè)參數(shù)就是我們觸發(fā)方法傳遞的數(shù)據(jù)了
- 通過(guò)action.payload拿到數(shù)據(jù)
addToNum(state, action) {
state.count = action.payload
}調(diào)用觸發(fā)
dispatch(addToNum(20))
2.異步操作獲取數(shù)據(jù)
(1).在源store外面定義一個(gè)異步函數(shù)并暴露出去,異步函數(shù)中調(diào)用dispatch()
dispatch中傳遞源store中reducer中的action對(duì)象
// channelStore.js (源)
// 解構(gòu)出action對(duì)象
const {setChannel} = channelStore.actions
// 封裝函數(shù)
const fetchChannelList = ()=>{
return async(dispatch) =>{
const res = await.get(url) // url是請(qǐng)求后端的地址
// setChannel是源store在reducer中定義的action對(duì)象
dispatch(setChannel(res.data.channels))
}
}注意,因?yàn)榻oaction對(duì)象傳遞參數(shù)了,所以參考上面的action傳參,需要源store中的action對(duì)象多定義一個(gè)action形參來(lái)接收數(shù)據(jù)
// channelStore.js (源)
reducers:{
setChannels(state,action){
state.channelList = action.payload
}
}(2).在需要的地方調(diào)用:
// App.js
const dispatch = useDispatch()
useEffect(()=>{
dispatch(fetchChannelList())
},[dispatch]以上就是React中使用Redux Toolkit狀態(tài)管理的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于React Redux Toolkit狀態(tài)管理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
ahooks封裝cookie?localStorage?sessionStorage方法
這篇文章主要為大家介紹了ahooks封裝cookie?localStorage?sessionStorage的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
React useMemo和useCallback的使用場(chǎng)景
這篇文章主要介紹了React useMemo和useCallback的使用場(chǎng)景,幫助大家更好的理解和學(xué)習(xí)使用React框架,感興趣的朋友可以了解下2021-04-04
react配置代理setupProxy.js無(wú)法訪問(wèn)v3.0版本問(wèn)題
這篇文章主要介紹了react配置代理setupProxy.js無(wú)法訪問(wèn)v3.0版本問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
一起來(lái)學(xué)習(xí)React元素的創(chuàng)建和渲染
這篇文章主要為大家詳細(xì)介紹了React元素的創(chuàng)建和渲染,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03

