我是react-redux新手,无法确定错误到底是什么。我得到的错误是 state.lectures.push 不是一个函数,但数据被发送到服务器和数据库,我也可以检索它,并且当我刷新时,数据也在前端更新。唯一烦人的部分是它无法正确渲染。
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { toast } from "react-toastify";
const initialState={
lectures:[],
}
export const addLecture = createAsyncThunk(
"addLecture",
async ({ c_id, formData }) => {
try {
const response = await fetch(`http://localhost:4000/addLecture/${c_id}`, {
method: "POST",
body: formData,
credentials: "include",
});
const resdata = await response.json();
console.log(resdata);
return resdata;
} catch (err) {
console.log(err);
}
}
);
export const getLectures = createAsyncThunk("getLectures", async (id) => {
try {
const response = await fetch(`http://localhost:4000/getLectures/${id}`, {
credentials: "include",
});
const res = await response.json();
console.log(res);
return res;
} catch (err) {
console.log(err);
}
});
export const RecordSlice = createSlice({
name: "lecture",
initialState,
reducers:{},
extraReducers: (builder) => {
builder.addCase(addLecture.fulfilled, (state, action) => {
state.lectures.push(action.payload)
console.log(action.payload);
});
builder.addCase(addLecture.rejected, (state, action) => {
console.log("error", action.payload);
});
builder.addCase(getLectures.fulfilled, (state, action) => {
state.lectures=action.payload;
console.log(action.payload);
});
builder.addCase(getLectures.rejected, (state, action) => {
console.log("error", action.payload);
});
},
});
export default RecordSlice.reducer;```
I have tried everything possible.[This is the error](https://i.stack.imgur.com/NsIec.png)`your text`
你必须将 React Redux 中的状态行为为不可变:而不是
state.lectures.push(action.payload)
使用:
state.lectures={...state.lecture,action.payload}
或者:
state={...state,lectures:{...lectures,action.payload}}