React使用Redux Toolkit的方法示例
一、什么是Redux Toolkit
1、概念
Redux Toolkit是一個官方支持的、用于簡化Redux開發(fā)的工具集。它提供了一些簡單易用的API和工具,可以幫助開發(fā)者更快速、更高效地編寫Redux應(yīng)用。
2、主要功能
簡化Redux的配置
Redux Toolkit提供了一個createSlice函數(shù),可以用來快速創(chuàng)建Redux的action和reducer,不需要手動編寫大量的模板代碼。
封裝常用的Redux函數(shù)
Redux Toolkit提供了一些封裝過的Redux函數(shù),如createAsyncThunk、createEntityAdapter等,這些函數(shù)可以幫助開發(fā)者更加容易地處理異步操作、管理實體數(shù)據(jù)等常見任務(wù)。
整合常用的中間件
Redux Toolkit默認集成了常用的中間件,如redux-thunk、redux-logger等,使得開發(fā)者可以更加便捷地使用這些中間件,而不需要手動配置。
提供默認的Redux store配置
Redux Toolkit提供了一個configureStore函數(shù),可以用來快速創(chuàng)建一個Redux store,并且默認配置了許多常用的中間件和插件,減少了開發(fā)者的配置工作量。
總結(jié)
總的來說,Redux Toolkit可以幫助開發(fā)者更加高效地使用Redux,減少了許多樣板代碼和配置工作,同時提供了一些常用的功能和工具,使得開發(fā)者可以更加專注于業(yè)務(wù)邏輯的實現(xiàn)
二、安裝
// 如果你已經(jīng)安裝了redux 和 react-redux,則不需要重復(fù)安裝 npm install @reduxjs/toolkit
三、簡單例子
實現(xiàn)數(shù)值加、減的功能
1、創(chuàng)建store.js文件
import { configureStore, createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, }, }); const store = configureStore({ reducer: counterSlice.reducer, }); export default store; export const { increment, decrement } = counterSlice.actions;
2、頁面中使用
import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { increment, decrement } from "./store"; function App() { const count = useSelector((state) => state.value); const dispatch = useDispatch(); return ( <div> <h1>Count: {count}</h1> <button onClick={() => dispatch(increment())}>+</button> <button onClick={() => dispatch(decrement())}>-</button> </div> ); } export default App;
四、redux-toolkit 中的 configureStore
1、概念
configureStore是Redux Toolkit中的一個工廠函數(shù),用于創(chuàng)建Redux store。它的目的是簡化Redux store的設(shè)置,并提供許多默認設(shè)置和內(nèi)置的中間件,使其更易于使用。
import { configureStore } from '@reduxjs/toolkit'; const store = configureStore({ // 一系列選項 });
2、選項詳解
1、reducer
reducer是必選項,指定應(yīng)用程序的根reducer函數(shù)??梢允且粋€單獨的reducer函數(shù),也可以是由多個reducer函數(shù)組成的對象。如果傳遞一個對象,則每個鍵將映射到應(yīng)用程序狀態(tài)中的相應(yīng)屬性。
2、preloadedState
應(yīng)用程序的初始狀態(tài)。這可以是從服務(wù)器獲取的數(shù)據(jù)或以其他方式獲得的數(shù)據(jù)。簡單理解為初始化的state
3、middleware
是一個數(shù)組,其中包含應(yīng)用程序使用的所有中間件。默認情況下,configureStore將使用以下中間件
redux-thunk: 支持使用異步action創(chuàng)建函數(shù)
redux-immutable-state-invariant: 檢查狀態(tài)是否被修改
redux-logger: 記錄Redux操作日志
4、devTools
一個布爾值,用于啟用或禁用Redux DevTools。如果值為true,則可以使用Redux DevTools來查看應(yīng)用程序狀態(tài)和操作日志。默認為true。
5、enhancers
它是一個數(shù)組,其中包含一組enhancer函數(shù)。enhancer是一種功能強大的Redux工具,可以用于增強或修改Redux store的行為??捎糜谔砑覴edux中間件、增強Redux DevTools或使用其他工具。
6、replayThunk
它是一個布爾值,指示是否要重放thunk中的操作日志。如果設(shè)置為true,則Redux store將回放thunk操作的歷史記錄,以便應(yīng)用程序狀態(tài)在重新加載時與之前一致。默認為false
7、serializableCheck
它一個布爾值,用于啟用或禁用Redux默認的序列化檢查。序列化檢查可確保Redux store的狀態(tài)可以被序列化為JSON字符串,并在重啟應(yīng)用程序時保持不變。默認為true。
8、serializableCheckOptions
一個對象,其中包含用于自定義序列化檢查的選項??捎糜诟男蛄谢瘷z查的錯誤消息或更改允許的數(shù)據(jù)類型。
3、總結(jié)
configureStore函數(shù)是一個創(chuàng)建Redux store的快捷方式,為開發(fā)者提供了一些常用的設(shè)置和默認選項,從而加快了開發(fā)速度。在大多數(shù)情況下,使用默認設(shè)置就足夠了,但如果需要自定義更多的選項,也可以通過傳遞一個選項對象來進行更改
五、edux-toolkit 中的 createReducer
1、概念
當(dāng)我們使用 Redux 開發(fā)應(yīng)用程序時,一個非常重要的概念就是 reducer。一個 reducer 是一個純函數(shù),它接受先前的狀態(tài)和一個動作,然后返回一個新狀態(tài)。每個動作都會引起狀態(tài)的變化,從而使應(yīng)用程序狀態(tài)管理更加清晰和可控。
在 Redux Toolkit 中,createReducer 方法是一個用于創(chuàng)建 reducer 的簡單工具,它可以將多個 reducer 函數(shù)組合成一個 reducer 函數(shù),并使用更簡潔的語法定義 reducer 函數(shù)。使用 createReducer 可以大大簡化編寫 reducer 函數(shù)的過程。
2、基本語法
1、基本語法
import { createReducer } from '@reduxjs/toolkit'; /* 最新版rtk已棄用 */ const initialState = { /* 初始狀態(tài) */ }; const myReducer = createReducer(initialState, { actionCreator1: (state, action) => { /* 處理 actionCreator1 */ }, actionCreator2: (state, action) => { /* 處理 actionCreator2 */ }, ... });
2、使用一個帶有多個 case 分支的 switch 語句來定義 reducer 函數(shù)
import { createReducer } from '@reduxjs/toolkit'; const initialState = { /* 初始狀態(tài) */ }; const myReducer = createReducer(initialState, (builder) => { builder .addCase(actionCreator1, (state, action) => { /* 處理 actionCreator1 */ }) .addCase(actionCreator2, (state, action) => { /* 處理 actionCreator2 */ }) ... });
3、例子
1、創(chuàng)建counter-reducer.js文件
const initialState = { // 初始狀態(tài) count: 0 }; // 使用createReducer創(chuàng)建Reducer函數(shù) const counterReducer = createReducer(initialState, { // 處理increment action increment: (state) => { state.count += 1; }, // 處理decrement action decrement: (state) => { state.count -= 1; }, // 處理reset action reset: (state) => { state.count = 0; } });
2、在store文件引入
import { configureStore } from '@reduxjs/toolkit'; import counterReducer from './counterReducer'; const store = configureStore({ reducer: counterReducer });
3、頁面中使用完成加、減、重置功能
import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; const Counter = () => { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <div> <h1>Count: {count}</h1> {/* dispatch方法中直接 調(diào)用定義的reducer的方法 */} <button onClick={() => dispatch({type: 'increment'})}>Increment</button> <button onClick={() => dispatch({type: 'decrement'})}>Decrement</button> </div> ); }; export default Counter;
六、redux-toolkit 中的 createAction
1、概念
createAction 是一個用于創(chuàng)建 Redux action creator 的函數(shù),它可以讓你更快地編寫 Redux 相關(guān)的代碼,并且更加易于閱讀和維護。
2、簡單示例
使用 createAction,你只需要傳入一個字符串類型的 action type,然后它會返回一個新的函數(shù),這個函數(shù)就是 Redux action creator。當(dāng)你調(diào)用這個新的函數(shù)時,它會返回一個包含 type 屬性的普通 JavaScript 對象,這個對象就是 Redux 中的 action。
import { createAction } from '@reduxjs/toolkit' const increment = createAction('counter/increment') // 使用新的action creator dispatch(increment()) // { type: 'counter/increment' }
3、使用createAction的好處
在實際使用中,createAction 的最大優(yōu)點在于它可以自動創(chuàng)建 FSA(Flux Standard Action)規(guī)范的 action,即一個帶有 type、payload 和 error 屬性的 action。這使得我們在編寫 Redux 相關(guān)的代碼時,可以更加標(biāo)準(zhǔn)化和規(guī)范化,同時也能夠更好地與其他庫和工具集成。
import { createAction } from '@reduxjs/toolkit' const addTodo = createAction('todos/add', (text) => ({ payload: { text } })) // 使用新的action creator dispatch(addTodo('Buy milk')) // { type: 'todos/add', payload: { text: 'Buy milk' } }
4、實際例子
1、創(chuàng)建reducers目錄并創(chuàng)建user.js文件
import { createReducer } from "@reduxjs/toolkit"; const userReducer = createReducer( { age: 1, name: "張三", }, (builder) => { builder .addCase("user/ageAdd", (state, action) => { state.age += 1; }) .addCase("user/updateName", (state, action) => { state.name = action.payload.name; }); } ); export default userReducer;
2、創(chuàng)建actions目錄并創(chuàng)建user.js文件
import { createAction } from "@reduxjs/toolkit"; /** * 接收兩個參數(shù) * 第一個參數(shù) 要調(diào)用reducer的名字 * 第二參數(shù) 是一個方法,接收調(diào)用時傳過來的參數(shù) * 返回一個payload的對象 */ export const ageAdd = createAction("user/ageAdd", () => { return { payload: {}, }; }); export const updateName = createAction("user/updateName", (name) => { return { payload: { name, }, }; });
3、在configureStore中掛載
import { configureStore, createReducer } from "@reduxjs/toolkit"; import userReducer from "./reducers/user"; export const countReducer = createReducer( { num: 1, }, { /** * 接收兩個參數(shù) * @param {} state 當(dāng)前的狀態(tài) * @param {*} action 頁面上傳過來的狀態(tài) */ add: (state, action) => { // 在這里面可以直接修改state 不需要return state.num += 1; }, } ); const store = configureStore({ // reducer: countReducer, reducer: userReducer, }); export default store;
4、頁面中使用
import { useSelector, useDispatch } from "react-redux"; import { ageAdd, updateName } from "./store/actions/user"; export default function LearnReduxToolkit() { const state = useSelector((state) => state); const dispatch = useDispatch(); return ( <div> <div> {state.name} - {state.age} </div> <button onClick={() => dispatch(ageAdd())}>age + 1</button> <input type="text" onChange={(event) => dispatch(updateName(event.target.value))} /> </div> ); }
七、切片
1、什么是切片
在 Redux 中,一個 state tree 是由多個 reducer 組成的,每個 reducer 負責(zé)管理一個 state 的一部分,這個概念稱為“切片”(slice)。
例如,一個電子商務(wù)應(yīng)用程序可能有一個購物車的 state,一個用戶信息的 state,以及一個商品列表的 state。每個 state 都可以由一個 reducer 管理,這些 reducer 可以通過 combineReducers 函數(shù)組合在一起,形成一個完整的 state tree。其中,每個 reducer 管理的部分 state 就是一個切片。
使用切片的好處在于,每個 reducer 只需要關(guān)心自己管理的部分 state,而不需要關(guān)心整個 state tree 的結(jié)構(gòu)。這樣可以使 reducer 的代碼更加清晰和易于維護。此外,切片還可以讓我們更加方便地組織 action creators 和 selectors,從而使代碼結(jié)構(gòu)更加清晰
2、什么是createSlice
createSlice是Redux Toolkit中提供的一個用于快速創(chuàng)建Redux reducer的函數(shù)。它基于Redux reducer的標(biāo)準(zhǔn)結(jié)構(gòu),使得創(chuàng)建和更新Redux state更加方便、簡潔。使用createSlice函數(shù)創(chuàng)建的slice包含了一個Redux reducer、一組action creators和對應(yīng)的action types。
3、createSlice解決了什么問題
createSlice 解決了傳統(tǒng) Redux 應(yīng)用中需要手動編寫 reducer 和 action creators 的問題,簡化了 Redux 應(yīng)用程序的開發(fā)流程,提高了代碼的可讀性和可維護性。
在傳統(tǒng)的 Redux 應(yīng)用程序中,我們需要手動編寫 reducer 函數(shù)來處理每個 action type,然后將它們組合成一個大的 rootReducer 函數(shù)。這樣的代碼結(jié)構(gòu)往往比較冗長和繁瑣,同時也容易出錯。而 createSlice 的出現(xiàn),讓我們可以通過提供一個包含 reducer 和 action creators 的對象來自動生成相應(yīng)的 reducer 函數(shù)和 action creators,從而避免了手動編寫 reducer 的過程,使得開發(fā)者更加專注于業(yè)務(wù)邏輯的實現(xiàn)。
4、createSlice的優(yōu)點
1、約定優(yōu)于配置
createSlice 使用一些約定俗成的規(guī)則來生成 reducer 和 action creators,例如使用 Immer 庫來進行 immutable state 的更新,這樣可以避免在編寫 reducer 函數(shù)時出現(xiàn)一些常見的錯誤。
2、自動生成 action type
createSlice 會自動根據(jù) slice 的名稱和 reducer 的名稱生成相應(yīng)的 action type,這樣就避免了手動編寫 action type 的過程,使得代碼更加規(guī)范化和易于維護。
3、簡化異步操
createSlice 提供了一個 createAsyncThunk 函數(shù),用于簡化異步操作的編寫流程,讓開發(fā)者更加專注于業(yè)務(wù)邏輯的實現(xiàn)
5、參數(shù)介紹
import { createSlice } from '@reduxjs/toolkit' /** * createSlice 返回當(dāng)前切片模塊 * 一個對象 */ const useSlice = createSlice({ // 切片名 name: 'sliceName', // 初始狀態(tài) initialState: { }, /** * reducer模塊 * 這里并不能進行異步操作 */ reducers: { // 里面直接跟方法 reducerName(state, action) { // handle the action return state } }, /** * 用于處理其他的 action type。 * 這些 reducer 函數(shù)也接收一個名為 state 的參數(shù)和一個名為 action 的參數(shù)。 * 注意,這些 reducer 函數(shù)默認沒有使用 Immer 庫進行 immutable state 的更新 */ extraReducers: { // handle extra reducers } }) // 導(dǎo)出相關(guān)的方法,頁面可以直接調(diào)用 export const { reducerName } = sliceName.actions // 當(dāng)前的的狀態(tài) export default sliceName.reducer
extraReducers
這里我們單獨介紹一下extraReducers。當(dāng)我們使用createSlice創(chuàng)建Redux的Slice時,extraReducers可以用于添加額外的reducer。這些額外的reducer可以處理來自其他Slice的action或其他非標(biāo)準(zhǔn)的action類型
1、在actions模塊中定義一個action
export const updateName = (name) => { return { type: 'updateName', name } }
2、在切片中引入
import { createSlice } from "@reduxjs/toolkit"; /** * createSlice 返回當(dāng)前切片模塊 * 一個對象 */ const userSlice = createSlice({ // 切片名 name: "user", // 初始狀態(tài) initialState: { age: 1, status: "", name: '張三' }, extraReducers: (builder) => { builder .addCase('updateName', (state, action) => { console.log(state, action, '當(dāng)前的動作') state.name = '王五' }) }, }); // 當(dāng)前的的狀態(tài) export default userSlice.reducer;
6、簡單例子實現(xiàn)age++
1、創(chuàng)建user模塊
import { createSlice } from '@reduxjs/toolkit' /** * createSlice 返回當(dāng)前切片模塊 * 一個對象 */ const userSlice = createSlice({ // 切片名 name: 'user', // 初始狀態(tài) initialState: { age: 1 }, /** * reducer模塊 * 這里并不能進行異步操作 */ reducers: { // 里面直接跟方法 addNum(state, action) { return {...state, age: state.age + 1} } }, }) // 導(dǎo)出相關(guān)的方法,頁面可以直接調(diào)用 export const { addNum } = userSlice.actions // 當(dāng)前的的狀態(tài) export default userSlice.reducer
2、頁面中調(diào)用
import React from "react"; import { useSelector, useDispatch } from "react-redux"; // import { increment, decrement } from "./store"; import { addNum } from "./slice/user"; function App() { const user = useSelector((state) => state.user); const dispatch = useDispatch(); return ( <div> {user.age} <button onClick={() => dispatch(addNum())}>age + 1</button> </div> ); } export default App;
八、redux-toolkit 中的 createAsyncThunk
1、概念
createAsyncThunk 是一個由 Redux Toolkit 提供的函數(shù),用于創(chuàng)建處理異步操作的 thunk action creator。使用 createAsyncThunk 可以簡化 Redux 中處理異步操作的流程,使代碼更加清晰、簡潔。
2、參數(shù)說明
import { createAsyncThunk } from "@reduxjs/toolkit"; const myAsyncThunk = createAsyncThunk( /** * 一個字符串類型的 action 名稱,用于在 Redux 中識別該 action。 * 該名稱通常包含操作名稱和狀態(tài) * */ "myAsyncOperationStatus", /** * 異步操作函數(shù),該函數(shù)接收兩個參數(shù) * 第一個參數(shù)是 thunk 的 payload,也就是調(diào)用的時候傳過來的 * 第二個參數(shù)是thunk對象 * dispatch * 用于 dispatch 其他 action 的函數(shù) * getState * 用于獲取當(dāng)前 Redux store 中的 state 的函數(shù) * extra * 性是用于傳遞額外參數(shù)的對象 * */ async (arg, { dispatch, getState, extra }) => { // 異步操作函數(shù),必須返回一個 Promise const response = await fetch("https://example.com/api/someEndpoint"); return response.json(); }, {} // 可選的配置項 );
3、例子
點擊按鈕age延遲1秒后+1,在延遲的時候,顯示loading。偶數(shù)的時候顯示報錯,并顯示提示信息
1、在action目錄的user.js文件添加一下代碼
import { createAction, createAsyncThunk } from "@reduxjs/toolkit"; const dely = () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }; export const ageAddAsync = createAsyncThunk( "user/ageAddAsync", async (arg, { dispatch, getState, extra }) => { const { user } = getState(); console.log(user.age); await dely(); // 偶數(shù)的時候拋錯 if (user.age % 2 === 0) { throw new Error("偶數(shù)的時候拋錯") } } );
2、修改slice目錄里的user.js模塊
import { createSlice } from "@reduxjs/toolkit"; import { ageAddAsync } from "./../actions/user"; const userSlice = createSlice({ // 切片名 必須全局唯一 name: "user", // 初始化狀態(tài) initialState: { age: 1, name: "李四", status: "", error: "", }, reducers: { /** * * @param {*} state 當(dāng)前的state * @param {*} action 穿過來的參數(shù) */ addAge(state, action) { return { ...state, age: state.age + 1, }; }, }, extraReducers: (builder) => { builder .addCase("user/updateName", (state, action) => { state.name = action.payload.name; }) // 異步方法的pedding狀態(tài) .addCase(ageAddAsync.pending, (state) => { state.status = "loading"; }) // 異步方法的成功的狀態(tài) .addCase(ageAddAsync.fulfilled, (state, action) => { state.age += 1; state.status = "successed"; state.error = '' }) /** * state * action 當(dāng)前的錯誤信息 */ .addCase(ageAddAsync.rejected, (state, action) => { console.log(action) state.status = "error"; state.age += 1 state.error = action.error.message; }); }, }); /** * 導(dǎo)出slice模塊的reducer */ export default userSlice.reducer; /** * 直接導(dǎo)出actions模塊 * 這個actions里面的方法和reducer里的方法名 * 一致,直接對象解構(gòu) */ export const { addAge } = userSlice.actions;
3、掛載到configureStore
import { configureStore, createSlice } from "@reduxjs/toolkit"; import user from './slice/user'; const store = configureStore({ reducer: { user }, }); export default store;
4、頁面中使用
import { useSelector, useDispatch } from "react-redux"; import { ageAddAsync } from "./store/actions/user"; export default function LearnReduxToolkit4() { const user = useSelector((state) => state.user); const dispatch = useDispatch(); return ( <div> <div> {user.name}--{user.age} </div> <div>{user.status}</div> <div>{user.error}</div> {/* <div>偶數(shù)拋出錯誤</div> */} <button onClick={() => dispatch(ageAddAsync())}>延遲一秒+1</button> </div> ); }
九、redux-toolkit 中的 createSelector
1、概念
在 Redux Toolkit 中,createSelector 是一個函數(shù),它允許我們從 Redux store 中選擇部分狀態(tài)數(shù)據(jù),并將其作為參數(shù)傳遞給一個 memoized 函數(shù),以避免在相同的輸入下重復(fù)計算。此外,Redux Toolkit 中的 createSelector 還支持嵌套選擇器和參數(shù)選擇器,使得選擇和組合 Redux store 中的狀態(tài)更加靈活
2、參數(shù)說明
import { createSelector } from '@reduxjs/toolkit' export const nameAndAge = createSelector( /** * 第一部分參數(shù)是一個或者多個輸入選擇器函數(shù) * 用戶選擇redux store中的一部分狀態(tài),并將其 * 作為計算函數(shù)的參數(shù) * 這些輸入選擇器函數(shù)可以是任何具有選擇狀態(tài)的功能 */ // 所有的state,導(dǎo)出user模塊給以下一位選手 (state) => state.user, (user) => { /** * 只有當(dāng)前模塊的數(shù)據(jù) * 發(fā)生改變的時候 * 才會觸發(fā)這一系列的方法 */ console.log("觸發(fā)了嗎") return { name: user.name, age: user.age } } )
3、簡單例子
1、在slice目錄下創(chuàng)建student
import { createSlice } from '@reduxjs/toolkit' const studentSlice = createSlice({ name: "student", initialState: { num: 1 }, reducers: { numAdd (state) { state.num += 1 } } }) export default studentSlice.reducer export const { numAdd } = studentSlice.actions
2、創(chuàng)建selectors目錄,在里面添加user.js文件
import { createSelector } from '@reduxjs/toolkit' export const nameAndAge = createSelector( /** * 第一部分參數(shù)是一個或者多個輸入選擇器函數(shù) * 用戶選擇redux store中的一部分狀態(tài),并將其 * 作為計算函數(shù)的參數(shù) * 這些輸入選擇器函數(shù)可以是任何具有選擇狀態(tài)的功能 */ // 所有的state,導(dǎo)出user模塊給以下一位選手 (state) => state.user, (user) => { /** * 只有當(dāng)前模塊的數(shù)據(jù) * 發(fā)生改變的時候 * 才會觸發(fā)這一系列的方法 */ console.log("觸發(fā)了嗎") return { name: user.name, age: user.age } } )
3、頁面中使用
import { nameAndAge } from "./store/selectors/user"; import { numAdd } from "./store/slices/student"; import { useSelector, useDispatch } from "react-redux"; import { useEffect } from "react"; export default function LearnReduxToolkit5() { /** * 如果要使用selector里面的數(shù)據(jù) * 那么必須要通過useSelector * 然后把對應(yīng)的方法傳入就可以拿到 * 返回值 */ const user = useSelector(nameAndAge); const dispatch = useDispatch(); useEffect(() => { console.log("觸發(fā)了嗎") }, [user]) const student = useSelector((state) => state.student); console.log(student); return ( <div> <div>{student.num}</div> <button onClick={() => dispatch(numAdd())}>+1</button> </div> ); }
4、使用場景
createSelector函數(shù)主要用于優(yōu)化React應(yīng)用程序中的性能,特別是在具有大量數(shù)據(jù)的情況下。它的主要用途是創(chuàng)建輸出選擇器函數(shù),該函數(shù)將redux store中的多個狀態(tài)組合并到單個值中,并將該值緩存以提高性能
1、過濾和排序數(shù)據(jù)
通過createSelector函數(shù),可以根據(jù)多個條件從Redux store中選擇數(shù)據(jù),并使用JavaScript函數(shù)對其進行過濾、排序等處理。
2、轉(zhuǎn)換數(shù)據(jù)格式
通過createSelector函數(shù),可以將Redux store中的原始數(shù)據(jù)轉(zhuǎn)換為更易于處理的格式,如圖表數(shù)據(jù),餅狀圖數(shù)據(jù)等。
3、避免不必要的渲染
使用createSelector函數(shù)可以避免不必要的渲染。當(dāng)createSelector函數(shù)的輸入?yún)?shù)未更改時,將從緩存中返回結(jié)果。只有當(dāng)輸入?yún)?shù)更改時,createSelector函數(shù)才會重新計算其輸出,并在React組件中觸發(fā)渲染。
4、避免重復(fù)計算
在Redux store中包含大量數(shù)據(jù)時,使用createSelector函數(shù)可以避免不必要的計算。例如,可以通過創(chuàng)建一個選擇器函數(shù),該函數(shù)選擇一個對象數(shù)組并返回其長度來避免在每次計算數(shù)組長度時進行重復(fù)的大量計算
到此這篇關(guān)于React使用Redux Toolkit的方法示例的文章就介紹到這了,更多相關(guān)Redux Toolkit使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react-router?v6實現(xiàn)動態(tài)路由實例
這篇文章主要為大家介紹了react-router?v6實現(xiàn)動態(tài)路由實例詳解,<BR>有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08詳解React中的useMemo和useCallback的區(qū)別
React中的useMemo和useCallback是兩個重要的Hooks。常常被用于優(yōu)化組件的性能。雖然這兩個Hooks看起來很相似,但它們彼此之間還是有很大的區(qū)別的,隨著小編一起來學(xué)習(xí)吧2023-04-04解決react?antd?Table組件使用radio單選框?更新選中數(shù)據(jù)不渲染問題
這篇文章主要介紹了解決react?antd?Table組件使用radio單選框?更新選中數(shù)據(jù)不渲染問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03React創(chuàng)建虛擬DOM的兩種方式小結(jié)
本文主要介紹了兩種創(chuàng)建React虛擬DOM的方式,包括JS方式和jsx方式,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01React?Fiber?樹思想解決業(yè)務(wù)實際場景詳解
這篇文章主要為大家介紹了React?Fiber?樹思想解決業(yè)務(wù)實際場景詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12React實現(xiàn)基于Antd密碼強度校驗組件示例詳解
這篇文章主要為大家介紹了React實現(xiàn)基于Antd密碼強度校驗組件示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01flouting?ui定位組件完美替代ant?deisgn使用詳解
這篇文章主要為大家介紹了flouting?ui定位組件完美替代ant?deisgn使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11