了解Redux Toolkit,這是用于高效Redux開發(fā)的經(jīng)過驗證的工具集。在本文中,你將看到為什么Redux Toolkit值得React社區(qū)更多的關(guān)注。
React和Redux被認為是大規(guī)模React應(yīng)用中管理狀態(tài)的最佳組合。然而,隨著時間的推移,Redux的受歡迎程度下降,原因是:
- 配置Redux Store并不簡單。
- 我們需要幾個軟件包來使Redux與React一起工作。
- Redux需要太多樣板代碼。
帶著這些問題,Redux的創(chuàng)建者Dan Abramov發(fā)表了名為《你可能不需要Redux》的文章,建議人們只在需要的時候使用Redux,而在開發(fā)不那么復(fù)雜的應(yīng)用時,要遵循其他方法。
Redux Toolkit解決的問題
Redux Toolkit(之前稱為Redux Starter Kit)提供了一些選項來配置全局store,并通過盡可能地抽象Redux API來更精簡地創(chuàng)建動作和reducers。
它包括什么?
Redux Toolkit附帶了一些有用的軟件包,例如Immer,Redux-Thunk和Reselect。它使React開發(fā)人員的工作變得更加輕松,允許他們直接更改狀態(tài)(不處理不可變性),并應(yīng)用Thunk之類的中間件(處理異步操作)。它還使用了Redux的一個簡單的“選擇器”庫Reselect來簡化reducer函數(shù)。
Redux Toolkit API的主要功能?
以下是Redux Took Kit使用的API函數(shù),它是現(xiàn)有Redux API函數(shù)的抽象。這些函數(shù)并沒有改變Redux的流程,只是以更易讀和管理的方式簡化了它們。
- configureStore:像從Redux中創(chuàng)建原始的createStore一樣創(chuàng)建一個Redux store實例,但接受一個命名的選項對象并自動設(shè)置Redux DevTools擴展。
- createAction:接受一個Action類型字符串,并返回一個使用該類型的Action創(chuàng)建函數(shù)。
- createReducer:接受初始狀態(tài)值和Action類型的查找表到reducer函數(shù),并創(chuàng)建一個處理所有Action類型的reducer。
- createSlice:接受一個初始狀態(tài)和一個帶有reducer名稱和函數(shù)的查找表,并自動生成action creator函數(shù)、action類型字符串和一個reducer函數(shù)。
您可以使用上述API簡化Redux中的樣板代碼,尤其是使用createAction和createReducer方法。然而,這可以使用createSlice進一步簡化,它可以自動生成action creator和reducer函數(shù)。
createSlice有什么特別之處?
它是一個生成存儲片的助手函數(shù)。它接受片的名稱、初始狀態(tài)和reducer函數(shù)來返回reducer、action類型和action creators。
首先,讓我們看看在傳統(tǒng)的React-Redux應(yīng)用程序中reducers和actions的樣子。
Actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import {GET_USERS,CREATE_USER,DELETE_USER} from "../constant/constants" ; export const GetUsers = (data) => (dispatch) => { dispatch({ type: GET_USERS, payload: data, }); }; export const CreateUser = (data) => (dispatch) => { dispatch({ type: CREATE_USER, payload: data, }); }; export const DeleteUser = (data) => (dispatch) => { dispatch({ type: DELETE_USER, payload: data, }); }; |
Reducers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import {GET_USERS,CREATE_USER,DELETE_USER} from "../constant/constants" ; const initialState = { errorMessage: "" , loading: false , users:[] }; const UserReducer = (state = initialState, { payload }) => { switch (type) { case GET_USERS: return { ...state, users: payload, loading: false }; case CREATE_USER: return { ...state, users: [payload,...state.users], loading: false }; case DELETE_USER: return { ...state, users: state.users.filter((user) => user.id !== payload.id), , loading: false }; default : return state; } }; export default UserReducer; |
現(xiàn)在,讓我們看看如何使用createSlice簡化并實現(xiàn)相同的功能。
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 { createSlice } from '@reduxjs/toolkit' ; export const initialState = { users: [], loading: false , error: false , }; const userSlice = createSlice({ name: 'user' , initialState, reducers: { getUser: (state, action) => { state.users = action.payload; state.loading = true ; state.error = false ; }, createUser: (state, action) => { state.users.unshift(action.payload); state.loading = false ; }, deleteUser: (state, action) => { state.users.filter((user) => user.id !== action.payload.id); state.loading = false ; }, }, }); export const { createUser, deleteUser, getUser } = userSlice.actions; export default userSlice.reducer; |
正如你所看到的,現(xiàn)在所有的動作和reducer都在一個簡單的地方,而在傳統(tǒng)的redux應(yīng)用中,你需要在reducer中管理每一個action和它對應(yīng)的action,當(dāng)使用createSlice時,你不需要使用開關(guān)來識別action。
當(dāng)涉及到突變狀態(tài)時,一個典型的Redux流程會拋出錯誤,你將需要特殊的JavaScript策略,如spread operator和Object assign來克服它們。由于Redux Toolkit使用Immer,因此您不必擔(dān)心會改變狀態(tài)。由于slice創(chuàng)建了actions和reducers,你可以導(dǎo)出它們,并在你的組件和Store中使用它們來配置Redux,而無需為actions和reducers建立單獨的文件和目錄,如下所示。
1
2
3
4
5
6
7
|
import { configureStore } from "@reduxjs/toolkit" ; import userSlice from "./features/user/userSlice" ; export default configureStore({ reducer: { user: userSlice, }, }); |
這個存儲可以通過使用useSelector和useDispatch的redux api直接從組件中使用。請注意,您不必使用任何常量來標(biāo)識操作或使用任何類型。
處理異步Redux流
為了處理異步動作,Redux Toolkit提供了一個特殊的API方法,稱為createAsyncThunk,它接受一個字符串標(biāo)識符和一個payload創(chuàng)建者回調(diào),執(zhí)行實際的異步邏輯,并返回一個Promise,該Promise將根據(jù)你返回的Promise處理相關(guān)動作的調(diào)度,以及你的reducers中可以處理的action類型。
1
2
3
4
5
6
7
8
|
import axios from "axios" ; import { createAsyncThunk } from "@reduxjs/toolkit" ; export const GetPosts = createAsyncThunk( "post/getPosts" , async () => await axios.get(`${BASE_URL}/posts`) ); export const CreatePost = createAsyncThunk( "post/createPost" ,async (post) => await axios.post(`${BASE_URL}/post`, post) ); |
與傳統(tǒng)的數(shù)據(jù)流不同,由createAsyncThunk處理的action將由分片內(nèi)的extraReducers部分處理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import { createSlice } from "@reduxjs/toolkit" ; import { GetPosts, CreatePost } from "../../services" ; export const initialState = { posts: [], loading: false , error: null , }; export const postSlice = createSlice({ name: "post" , initialState: initialState, extraReducers: { [GetPosts.fulfilled]: (state, action) => { state.posts = action.payload.data; }, [GetPosts.rejected]: (state, action) => { state.posts = []; }, [CreatePost.fulfilled]: (state, action) => { state.posts.unshift(action.payload.data); }, }, }); export default postSlice.reducer; |
請注意,在extraReducers內(nèi)部,您可以處理已解決(fulfilled)和已拒絕(rejected)狀態(tài)。
通過這些代碼片段,您可以看到此工具包在Redux中簡化代碼的效果如何。我創(chuàng)建了一個利用Redux Toolkit的REST示例供您參考。
最后的想法
根據(jù)我的經(jīng)驗,當(dāng)開始使用Redux時,Redux Toolkit是一個很好的選擇。它簡化了代碼,并通過減少模板代碼來幫助管理Redux狀態(tài)。
最后,就像Redux一樣,Redux Toolkit并非僅為React構(gòu)建。我們可以將其與其他任何框架(例如Angular)一起使用。
您可以通過參考Redux Toolkit的文檔找到更多信息。
謝謝您的閱讀!
以上就是如何使用Redux Toolkit簡化Redux的詳細內(nèi)容,更多關(guān)于使用Redux Toolkit簡化Redux的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://juejin.cn/post/6948083602529714184