简体   繁体   English

手动改变 React 上的状态,然后调用 setState

[英]Mutating state on React manually, then calling setState

I'm studying React JS making a simple todo list and part of my code is as follows:我正在研究 React JS 制作一个简单的待办事项列表,我的部分代码如下:

changeStatus(e, index) {
    this.state.tasks[index].status = e.target.value;
    this.setState((prevState) => ({
        tasks: prevState.tasks
    }));
}

As React documentation says, we shouldn't change state manually, we should call setState instead, so, I'm receiving a warning on console saying that, even calling setState after the manual changing.正如 React 文档所说,我们不应该手动更改state ,而应该调用setState ,因此,我在控制台上收到警告,甚至在手动更改后调用setState

I'm doing so because, for me, is more practical doing that than separating the task , doing a splice on my array, and calling setState with the new values.我这样做是因为,对我来说,这样做比分离task 、对数组进行splice并使用新值调用setState更实用。

Is there a problem with my approach?我的方法有问题吗? How would you recommend updating state in a efficient and non-repetitive way?您如何建议以有效且非重复的方式更新状态?

Try this :试试这个:

   changeStatus(e, index) {
      const tmp = { ...this.state };
      tmp.tasks[index].status = e.target.value;
      this.setState(tmp);
   }

You should not mutate the state directly, to do that create a new object from the state and then update that and set it back to state like你不应该直接改变状态,这样做从状态创建一个新对象,然后更新它并将其设置回状态

changeStatus(e, index) {
    var tasks = {...this.state.tasks}
    tasks[index].status = e.target.value;
    this.setState({tasks});
}

In case you are wondering as to what {...this.state.tasks} do then check this answer:如果您想知道{...this.state.tasks}做什么,请查看以下答案:

What is the meaning of this syntax "{...x}" in Reactjs Reactjs中这种语法“{...x}”的含义是什么

However you can also make a copy of the state using the ES5 Object.assign() operator like但是,您也可以使用ES5 Object.assign() 运算符制作状态的副本,例如

var tasks = Object.assign({}, this.state.tasks)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM