一、使用异步方法,需要 createAsyncThunk 函数
1.首先在特定的ts文件中建立异步
const fetchArticles=createAsyncThunk(
'searchArticle/fetchArticles',
async({SearchKey,type},thunkAPI)=>{
const params = {
Filter: SearchKey,
PageSize: 10,
PageNum: 1,
ArticleType: "",
};
const res: any = await GteArticleListApi(params);
const state = thunkAPI.getState();
console.log("文章列表",res.ArticleList, state.searchArticle.ArticleList);
if (type) {
const newArticle = state.searchArticle.ArticleList.concat(res.ArticleList);
return newArticle
} else {
return res.ArticleList
}
}
)
2.函数接收为两个值,一个是参数(如果有多个参数,请使用对象方式进行传参),另一个是thunkAPI(一个包含dispatch、getState和extra属性的对象,可以用于在异步操作中进行状态更新或其他操作),如果想要获取initialState的state的值,这个参数比不可少。
同时配置
extraReducers:(builder)=>{
builder.addCase(fetchArticles.fulfilled,(state,action)=>{
state.ArticleList=action.payload
})
}
3.异步函数的调用
先引入:
import { fetchArticles } from "@/store/modules/searchArticle";
再使用:
dispatch(
fetchArticles({ SearchKey: getSearchArr.getAll("SearchKey")[0], type: 0 })
)
注意:记得再redux的ts文件中导出 export {fetchArticles}
最后,附上整个使用方法:
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { GteArticleListApi } from "@/http/api/article";
const fetchArticles=createAsyncThunk(
'searchArticle/fetchArticles',
async({SearchKey,type},thunkAPI)=>{
const params = {
Filter: SearchKey,
PageSize: 10,
PageNum: 1,
ArticleType: "",
};
const res: any = await GteArticleListApi(params);
const state = thunkAPI.getState();
console.log("文章列表",res.ArticleList, state.searchArticle.ArticleList);
if (type) {
const newArticle = state.searchArticle.ArticleList.concat(res.ArticleList);
return newArticle
} else {
return res.ArticleList
}
}
)
export const searchArticle=createSlice({
name:"searchArticle",
initialState:{
ArticleList:[]
},
reducers:{
},
extraReducers:(builder)=>{
builder.addCase(fetchArticles.fulfilled,(state,action)=>{
state.ArticleList=action.payload
})
}
})
export const {} =searchArticle.actions
export default searchArticle.reducer
export {fetchArticles}
@reduxjs/toolkit还有更多的使用方法:可参考官网:入门 Redux | Redux 中文官网