更新状态-为什么在调用setState时创建新的状态副本? [英] Updating state - why creating a new copy of state when calling setState?

查看:64
本文介绍了更新状态-为什么在调用setState时创建新的状态副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反应文档:

切勿直接更改 this.state ,因为此后会调用 setState()可能会取代您所做的突变.将 this.state 视为不变的.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

很清楚.

class App extends React.Component {
  state = {
   data: []
  } 

以下我了解的

  updateState(event) {
   const {name, value} = event.target;
   let user = this.state.user; // this is a reference, not a copy...
   user[name] = value; // 
   return this.setState({user}); // so this could replace the previous mutation
  }

我不理解以下内容

  updateState(event) {
  const {name, value} = event.target;
  let user = {...this.state.user, [name]: value};
  this.setState({user});
  }

我了解(如前面的示例所示),我不仅应该:

I understand (as in previous example), that I should not either only:

  1. 直接更改状态,而无需调用setState;或
  2. 对其进行变异,然后再使用setState.

但是,为什么我不能(没有直接突变)调用setState 而没有创建新的状态副本(没有散布运算符/ Object.assign )?以下内容有什么问题?

However, why can't I just (without direct mutation) call setState without creating a new copy of state (no spread operator/Object.assign)? What would be wrong with the following:

  getData = () => {
   axios.get("example.com") ...
    this.setState({
     data:response.data
    })
  } 

为什么会这样:

  getData = () => {
   axios.get("example.com") ...
    this.setState({
     data:[...data, response.data]
    })
  } 

 render (){ 
  ...
 }  
}

推荐答案

以下内容可能有什么问题:

this.setState({
   data: response.data,
});

绝对没有,除非您不想将 this.state.data 的内容替换为 response.data .

Absolutely nothing, unless you don't want to replace the contents of this.state.data with response.data.

为什么要这样:

this.setState({
   data: [...data, response.data],
});

由于传播,您不会丢失 this.state.data 的内容-您基本上是将新的响应推送到 data 数组中.

Because with spread you are not loosing the contents of this.state.data - you are basically pushing new response into the data array.

注意:您应该在 setState 内部使用回调,以从 this.state 访问当前的数据.

Note: You should use callback inside setState to get access to current data from this.state.

this.setState((prevState) => ({
   data: [...prevState.data, response.data],
}));

这篇关于更新状态-为什么在调用setState时创建新的状态副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆