gpt4 book ai didi

javascript - 在设置状态之前 react 状态分配

转载 作者:行者123 更新时间:2023-11-30 00:03:23 24 4
gpt4 key购买 nike

我是 React 新手,正在学习在线教程。讲师将下面的代码作为 Todo 应用程序的一部分进行展示。这是将新的 todo 项(对象)添加到 state 的逻辑。

var TodoApp = React.createClass({
getInitialState: function() {
return {
todos: {}
};
},
addTodo: function(todo) {
var timestamp = (new Date()).getTime();
this.state.todos[`todo-${timestamp}`] = todo;
this.setState({
todos: this.state.todos
});
}
});

1. 在这种情况下,在调用 this.setState() 之前将 todo 对象分配给状态是否是一个好习惯? ? (这个SO question给出了一些相关信息。)
2.todos如下展开不是更好吗?
3. 或者,是否有更好的方法来更新此设置中的state

var TodoApp = React.createClass({
getInitialState: function() {
return {
todos: {}
};
},
addTodo: function(todo) {
var timestamp = (new Date()).getTime();
this.setState({
todos: {...this.state.todos, [`todo-${timestamp}`]: todo}
});
}
});

最佳答案

  1. 否,请参阅下面的示例和文档。

    this.state.todos = ...
    // Someone modifies todo's state at this point
    this.setState({
    todos: this.state.todos // this would not do what you expected anymore
    });

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made

React's documentation

  1. 当然,这就是 React 的方式。这是一个完美的解决方案。
  2. 传播就足够了。

关于javascript - 在设置状态之前 react 状态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com