Har*_*ngh 2 reactjs redux-toolkit
我正在尝试使用 redux-toolkit 来存储来自 api 的数据。我尝试过,但收到此错误,提示“对象表示法createSlice.extraReducers已被删除。请改用‘构建器回调’表示法”这是代码片段:
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
export const getAllJobs=createAsyncThunk("jobDetails",async ()=>{
const data = await fetch(" http://localhost:3031/jobs");
const result = data.json();
return result
})
export const jobDetails=createSlice({
name:"jobDetails",
initialState:{
jobs:[],
loading:false,
error:null,
},
extraReducers:{
[getAllJobs.pending]: (state)=>{
state.loading=true;
},
[getAllJobs.fulfilled]: (state,action)=>{
state.loading=false;
state.jobs=action.payload;
},
[getAllJobs.rejected]: (state,action)=>{
state.loading=false;
state.error=action.payload;
},
},
})
export default jobDetails.reducer;
Run Code Online (Sandbox Code Playgroud)
和商店
import {configureStore} from '@reduxjs/toolkit'
import jobDetails from '../features/jobSlice'
export const store= configureStore({
reducer: {
app: jobDetails
},
})
Run Code Online (Sandbox Code Playgroud)
我正在尝试将获取的 api 数据存储到作业中
自版本 1.9.0 以来createSlice.extraReducers已弃用 的对象语法,并在 v2.0.0 中删除。v2.0.0 变更日志以及RTK 2.0 和 Redux 5.0 的迁移指南中都解释了如何修复它。正如错误所述,您必须将对象转换为构建器回调语法:
举个例子:
Run Code Online (Sandbox Code Playgroud)const todoAdded = createAction('todos/todoAdded') createReducer(initialState, { [todoAdded]: (state, action) => {} }) createSlice({ name, initialState, reducers: { /* case reducers here */ }, extraReducers: { [todoAdded]: (state, action) => {} } })应该迁移到:
Run Code Online (Sandbox Code Playgroud)createReducer(initialState, builder => { builder.addCase(todoAdded, (state, action) => {}) }) createSlice({ name, initialState, reducers: { /* case reducers here */ }, extraReducers: builder => { builder.addCase(todoAdded, (state, action) => {}) } })
今后,遇到此类错误时,请务必在变更日志中搜索以查找示例。