嗨,我正在通过开发一个小应用程序来学习钩子的概念。我正在使用 redux 切片。我没有按照传统的方式来创建状态([state, setState]),而是在一个名为 intialState 的变量下创建状态。我试图通过点击外部 API 在应用程序中执行 CRUD 操作。我试图通过单击按钮从列表中删除值。在 intialState 变量下,我有一个名为 courses:[] 的状态,我曾经在其中存储来自终点的数据。当我执行删除操作时,我想为此课程setState。我试图设置状态,但最终出现错误。任何人都可以帮助我解决如何在下面的方法中设置状态。提前致谢。下面是我的代码。
const initialState = {
isLoading: false,
error: false,
courses: [],
};
//------------------Delete Course
export function deleteCourse(index, id) {
console.log('I am coming');
axios.delete(`edu/course/${id}`).then(res => {
const newCourseList = [...initialState.courses];
console.log('NEW COURSE LIST', newCourseList);
newCourseList.splice(index, 1);
setinitialState({ courses: newCourseList }); // If I am doing like this I am getting an
error
});
}
答案 0 :(得分:0)
在 react 中设置参数时要小心。您有一个名为 initialState 的变量,但您没有像 setinitialState 这样的变量,但这正是 react 提供我们以这种方式使用 set 更改变量的关键。但是 creaful 的一个重要点是你应该像 setVariableValues 这样使用它
setinitialState({ courses: newCourseList });
改为
setInitialState({ courses: newCourseList });
希望有效;)
答案 1 :(得分:0)
我猜这个问题/错误与在您设置 courses
状态时删除其余状态有关。
setinitialState({ courses: newCourseList }); // <-- fully replaces state
回想一下,在功能组件中,状态更新不是浅合并的。
<块引用>与类组件中的 setState 方法不同,useState 不会 不会自动合并更新对象。你可以复制这个 通过将函数更新器形式与对象传播相结合来实现行为 语法:
const [state, setState] = useState({});
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});
使用函数状态更新从之前的状态更新,浅拷贝之前的状态然后使用过滤器函数通过匹配索引过滤课程数组。
export function deleteCourse(index, id) {
axios.delete(`edu/course/${id}`).then(res => {
setinitialState(prevState => ({
...prevState,
courses: prevState.courses.filter((_, i) => i !== index),
}));
});
}