React中使用Redux Toolkit狀態(tài)管理的示例詳解
一、什么是源 Store 和根 Store?
這里只是自己覺得這樣定義會更好理解一些,實際并沒有這樣的概念
源 Store
源 store 是模塊化的狀態(tài)管理單元,負責特定功能的狀態(tài)和操作。使用 createSlice
創(chuàng)建的 slice 就是源 store。
類比:可以想象成一個專注于特定產(chǎn)品的車間,例如一個玩具制造車間。它只負責制造特定類型的玩具(如計數(shù)器的狀態(tài)管理),并且有自己的一套操作流程(增、減、重置)。
根 Store
根 store 是整個應用的狀態(tài)管理中心,使用 configureStore
組合多個源 store。它負責將所有的狀態(tài)和邏輯集中起來,提供給整個應用使用。
類比:可以想象成一個大型工廠,里面有多個車間(源 store)。有負責制造玩具的,有負責制造家具的。。。這個工廠負責管理和協(xié)調(diào)各個車間的生產(chǎn),并且能夠根據(jù)需求調(diào)整生產(chǎn)線(即添加或修改源 store)。
二、創(chuàng)建 Counter Store
2.1 定義源 Store
在一個新的文件 counterSlice.js
中,我們將創(chuàng)建計數(shù)器的 slice:
// store/modules/xxx.js import { createSlice } from '@reduxjs/toolkit'; // 創(chuàng)建一個 slice const counterSlice = createSlice({ name: 'counter', // 定義 slice 的名稱 initialState: { // 初始化狀態(tài) count: 0, // 需要被全局維護的數(shù)據(jù) }, reducers: { // 定義修改狀態(tài)的方法 increment(state) { state.count += 1; // 增加計數(shù) }, decrement(state) { state.count -= 1; // 減少計數(shù) }, reset(state) { state.count = 0; // 重置計數(shù) }, }, }); // 導出 action 對象 export const { increment, decrement, reset } = counterSlice.actions; // 導出 reducer 函數(shù) export const counterReducer = counterSlice.reducer;
在這個例子中,counterSlice 就是我們的源 store,它初始化了一個 count 狀態(tài),并提供了三個 reducers 來修改這個狀態(tài)。
三、組合 Store(根)
在另一個文件 store.js 中,我們將使用 configureStore 來組合根 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,它可以容納多個源 store(在本例中只有 counter
),并將它們組合在一起進行集中管理。
根store中可以定義多個源store,這里只示例一個
四、連接 React 和 Redux
我們目前只是使用了源store中的reducer函數(shù)來組合根store,還有定義導出的源store中的action對象并沒有使用
現(xiàn)在我們已經(jīng)定義了 store,但還需要將其鏈接到我們的 React 應用中。我們將使用 react-redux 中的 Provider 組件來實現(xiàn)這一點。
4.1 綁定 Store(為組件注入store)
在 index.js
或 App.js
中,我們將 Provider
組件包裹住我們的應用:
// 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
鉤子來訪問 store 中的狀態(tài),并使用 useDispatch
鉤子來觸發(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;
在這個組件中,我們通過 useSelector
獲取 count
狀態(tài),并通過 useDispatch
觸發(fā) increment
、decrement
和 reset
這三個 action。
總結
通過以上步驟,我們成功使用 Redux Toolkit 創(chuàng)建了一個簡單的計數(shù)器應用。整個過程包括:
- 定義源 store(創(chuàng)建 slice)。
- 將源 store 組合到根 store 中。
- 通過
Provider
注入 store 到 React 應用中。 - 使用
useSelector
和useDispatch
連接組件與 store,實現(xiàn)狀態(tài)管理。
擴展:
1.action傳參:
- 對源store的reducer中的action對象多傳遞一個action參數(shù),這個參數(shù)就是我們觸發(fā)方法傳遞的數(shù)據(jù)了
- 通過action.payload拿到數(shù)據(jù)
addToNum(state, action) { state.count = action.payload }
調(diào)用觸發(fā)
dispatch(addToNum(20))
2.異步操作獲取數(shù)據(jù)
(1).在源store外面定義一個異步函數(shù)并暴露出去,異步函數(shù)中調(diào)用dispatch()
dispatch中傳遞源store中reducer中的action對象
// channelStore.js (源) // 解構出action對象 const {setChannel} = channelStore.actions // 封裝函數(shù) const fetchChannelList = ()=>{ return async(dispatch) =>{ const res = await.get(url) // url是請求后端的地址 // setChannel是源store在reducer中定義的action對象 dispatch(setChannel(res.data.channels)) } }
注意,因為給action對象傳遞參數(shù)了,所以參考上面的action傳參,需要源store中的action對象多定義一個action形參來接收數(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)管理的示例詳解的詳細內(nèi)容,更多關于React Redux Toolkit狀態(tài)管理的資料請關注腳本之家其它相關文章!
相關文章
在react中對less實現(xiàn)scoped配置方式
這篇文章主要介紹了在react中對less實現(xiàn)scoped配置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11React調(diào)度系統(tǒng)Scheduler工作原理詳解
這篇文章主要為大家介紹了React調(diào)度系統(tǒng)Scheduler工作原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03react.js 獲取真實的DOM節(jié)點實例(必看)
下面小編就為大家?guī)硪黄猺eact.js 獲取真實的DOM節(jié)點實例(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04詳解使用create-react-app快速構建React開發(fā)環(huán)境
這篇文章主要介紹了詳解使用create-react-app快速構建React開發(fā)環(huán)境,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05React源碼分析之useCallback與useMemo及useContext詳解
這篇文章主要介紹了React useCallback與useMemo及useContext源碼分析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-11-11