我还是本机和反应的新手,所以我正在关注本教程的 todo 应用程序并阅读以下文章:https://lorenstewart.me/2017/01/22/javascript-array-methods-mutating-vs-non-mutating/https://daveceddia.com/why-not-modify-react-state-directly/addNewTodo 方法使用 unshift,如果我没记错的话它会改变数组/状态吗?有没有更有效的方法来写这个在 add 方法上传播?或者,如果我完全错了并且很好,那么使用反应工具确定状态是否正在发生变化(比如维护其他 ppl 代码)有什么好方法?export default class App extends React.Component { constructor(){ super(); this.state = { todoInput: '', todos: [ {id: 0, title: 'Insult Jerry', done: false}, {id: 1, title: 'Build something', done: false}, {id: 2, title: 'Morty Mind Blowers', done: false} ] } } addNewTodo () { let todos = this.state.todos; todos.unshift({ id: todos.length + 1, title: this.state.todoInput, done: false }); this.setState({ todos, todoInput: '' }); } toggleDone (item) { let todos = this.state.todos; todos = todos.map((todo) => { if (todo.id == item.id) { todo.done = !todo.done; } return todo; }) this.setState({todos}); } removeTodo (item) { let todos = this.state.todos; todos = todos.filter((todo) => todo.id !== item.id); this.setState({todos}); }...
1 回答

犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
您可以使用扩展运算符而不是unshift这样:
this.setState({
todos: [
{
id: this.state.todos.length + 1,
title: this.state.todoInput,
done: false
},
...this.state.todos
]
});
我不知道有任何工具可以让您确定状态是否正在发生变化。但是如果你准备使用 TypeScript,你可以声明状态readonly以防止这种类型的突变。
添加回答
举报
0/150
提交
取消