简介
-
我是使用axios来进行异步请求 ,安装请点击
-
我们一般使用
createAsyncThunk
来创建一个异步请求点击- createAsyncThunk创建一个异步的action,这个方法被触发的时候会有三个状态
pending(进行中)
、fulfilled(成功)
、rejected(失败)
- 返回一个标准的
Redux thunk action creator
。thunk动作创建器函数将为pending, fulfilled, rejected情况提供普通action creator,并将其作为嵌套字段附加
- createAsyncThunk创建一个异步的action,这个方法被触发的时候会有三个状态
参数
- actionType字符串(如
weather/loadPic
), rtk会会基于此生成以下三个action creator,具体点击
pending: 'weather/loadPic/pending'
fulfilled: 'weather/loadPic/fulfilled'
rejected: 'weather/loadPic/rejected'
payloadCreator
:回调函数,他应该返回一个值,且这个值会在fulfilled
的action creater
中作为payload
的值,他一般返回一个promise
export const loadPic = createAsyncThunk('weather/loadPic', async () => {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("后台返回的数据")
},2000)
})
});
- 在前台我们要await来等待数据
const handleWeather = async() => {
// 在这里dispatch返回一个promise
const res = await dispatch(loadPic())
console.log("组件",res);
}
例子
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios'
import { increment } from './counterSlice';
// axios返回promise
const loadPicAPI = () => axios.get("https://bird.ioliu.cn/v1?url=http://www.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1")
export const loadPic = createAsyncThunk('weather/loadPic', async () => {
const res = await loadPicAPI();
return res; // 此处的返回结果会在 .fulfilled中作为payload的值
});
export const weatherSlice = createSlice({
name: 'weather',
initialState: {
weather:""
},
reducers: {
loadWeatherData(state, { payload }) {
state.weather = payload;
},
},
// 可以额外的触发其他slice中的数据关联改变
extraReducers: {
[loadPic.fulfilled](state, { payload }) {
console.log("payload",payload);
console.log("111111111");
increment({step:3})
state.weather = payload.data.images[0].copyrightlink;
},
[loadPic.rejected](state, err) {
console.log(err);
},
[loadPic.pending](state) {
console.log('进行中');
},
},
});
export const { loadWeatherData } = weatherSlice.actions;
export default weatherSlice.reducer;
extraReducers
除了跟一个对象外,还可以跟一个函数,点击
createSlice({
...
extraReducers: builder => {
builder.addCase(loadPic.fulfilled, (state, action) => {
console.log(action);
state.weather = action.payload.data.images[0].copyrightlink;
})
}
})
- 在实例当中
createAsyncThunk
会生成三对action
和action creater
,在适当的时机就会触发,相应的action creater
pending: 'weather/loadPic/pending'
fulfilled: 'weather/loadPic/fulfilled'
rejected: 'weather/loadPic/rejected'
报错
- 在我们使用的时候可能会遇到报错,我们可以做如下处理
因为redux存储时是将数据序列化后存储的,并且@reduxjs/toolkit
里面会默认检查是否序列化
export default configureStore({
reducer: {
counter: counterSlice,
weather: weatherSlice
},
middleware:(getDefaultMiddleware)=> getDefaultMiddleware({serializableCheck:false})
});