九口袋網(wǎng)站建設(shè)免費(fèi)b站推廣
簡單使用
1、下載
npm i @reduxjs/toolkit react-redux
2、創(chuàng)建
????1、在redux/user.js中創(chuàng)建模塊user。從@reduxjs/toolkit中引入createSlice創(chuàng)建模塊片段,我們需要傳入name、初始數(shù)據(jù)initialState、改state的reducers等。最后需要導(dǎo)出reducer和action。
代碼如下:
import { createSlice } from '@reduxjs/toolkit'const userSlice = createSlice({name: 'user', //action.type和reducer的名字,表現(xiàn)在控制臺的調(diào)試器上,一般與模塊同名//初始數(shù)據(jù)initialState: {age: 18},reducers: {// reducers中存放用于修改state的方法changeAge(state, action) {state.age = action.payload //傳過來的數(shù)據(jù)存放在action.payload上}}
})export const { changeAge } = userSlice.actions //需要把a(bǔ)ction導(dǎo)出,dispatch需要
export default userSlice.reducer //導(dǎo)出reducer,用于創(chuàng)建Store
????????2、在redux/index.js中,引入configureStore用于創(chuàng)建Store,還需要引入user模塊的reducer完成創(chuàng)建。代碼如下:
import { configureStore } from '@reduxjs/toolkit'
import userReducer from './user'const Store = configureStore({reducer: {user: userReducer //模塊名:reducer}
})export default Store
3、在index.js中與之前一樣,引入Provider,傳入Store。
import React from 'react'
import ReactDOM from 'react-dom/client'import App from './App'
import Store from './redux'
import { Provider } from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(// 將store傳入context,這樣任何組件都能訪問Store,而不需要在組件中手動引入Store<Provider store={Store}><App /></Provider>
)
3、使用
在jsx文件中,dispatch的是前面user模塊文件導(dǎo)出的action。代碼如下:
import React from 'react'
import { changeAge } from './redux/user'
import { useDispatch, useSelector } from 'react-redux'
export function About() {const dispatch = useDispatch()const age = useSelector((state) => state.user.age)function addAge() {dispatch(changeAge(age + 1))}return (<div>年齡{age}<button onClick={addAge}>增加+</button></div>)
}
export default About
異步操作:createAsyncThunk
簡單方式
????????在redux/uset.js文件中,定義一個(gè)action方法用于修改state。在導(dǎo)出這個(gè)方法的后面,引入createAsyncThunk創(chuàng)建thunk方法。在這個(gè)方法的回調(diào)中會接收store,我們可以在請求到數(shù)據(jù)之后觸發(fā)dispatch完成state的修改,具體代碼如下:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'const userSlice = createSlice({name: 'user', //action.type和reducer的名字,表現(xiàn)在控制臺的調(diào)試器上,一般與模塊同名//初始數(shù)據(jù)initialState: {data: []},reducers: {setData(state, { payload }) {state.data = payload}}
})export const { setData } = userSlice.actions //需要把a(bǔ)ction導(dǎo)出,dispatch需要
// 在導(dǎo)出action的下方定義thunk方法
export const getDataThunk = createAsyncThunk('user/getData', async (id, store) => {let res = await fetch(`http://localhost:3000/data.txt?id=${id}`)res = await res.json()store.dispatch(setData(res))
})
export default userSlice.reducer //導(dǎo)出reducer,用于創(chuàng)建Store
? ? ? ? 使用就是正常的dispatch這個(gè)thunk
import { getDataThunk} from './redux/user'await dispatch(getDataThunk()) //因?yàn)榉祷豴romise,我們可以await,這樣就是同步的啦
其他方式
? ? ? ? 另外的方法是先定義好thunk方法,然后在slice配置對象中使用extraReducers函數(shù),函數(shù)接收builder,利用builder.addCase添加回調(diào),完成對state的修改。
????????代碼如下:【但是我覺得上面的寫法更簡單】
// 利用createAsyncThunk創(chuàng)建異步action,第一個(gè)參數(shù)是 'action名' ,第二個(gè)參數(shù)是回調(diào)用于請求接口,用promise返回?cái)?shù)據(jù)
export const fetchUser = createAsyncThunk('fetchUser', async (userId) => {let res = await fetch('http://123.207.32.32:8000/home/multidata')res = await res.json()return res
})
{name:'user',initialState:{//...},reducer:{//...},extraReducers: (builder) => {builder// .addCase(fetchUser.pending, (state) => {// state.loading = true;// }).addCase(fetchUser.fulfilled, (state, action) => {state.list = action.payload})// .addCase(fetchUser.rejected, (state, action) => {// state.loading = false;// state.error = action.payload;// });},// 下面的寫法有警告
/* extraReducers: {[fetchUser.pending](state, action) {// state.list = action.payload// 做一些加載轉(zhuǎn)圈的操作console.log('pending');},[fetchUser.fulfilled](state, action) {state.list = action.payload},[fetchUser.rejected](state, action) {// state.list = action.payloadconsole.log('rejected');}} */
}
END
redux有關(guān)的知識暫時(shí)總結(jié)完畢。