【问题标题】:What is the proper way to handle component's state in React?在 React 中处理组件状态的正确方法是什么?
【发布时间】:2016-07-13 02:20:11
【问题描述】:

我见过人们使用setState 方式:

this.setState( {enteredlocation: newLocation});

目前我正在写这样的状态:

this.state.id.push({"no" : length , "location": this.state.enteredlocation});

更新状态的正确方法是什么?

稍后我也将集成 Redux,但现在,我正在尝试部分理解。

【问题讨论】:

  • 正确的方法是使用this.setStateNEVER直接改变this.state对象。顺便说一句,我确信this.state.id.push() 不会触发组件重新渲染,所以这个调用的用处并不明显。
  • 是的,使用this.state.id.push() 时它不会重新渲染,这让我很困惑为什么。对此有解释吗?我想我会使用this.setState
  • "有对此的解释吗?" --- 当然:react 不知道您刚刚所做的更改。
  • 所以基本上,你的意思是只有当我们只使用this.setState 时,react 才能知道变化?还有其他方法可以正常返回新状态吗?
  • 你没有“归还”它——你“设置”了它。 this.setState - 设置组件的新状态。

标签: javascript reactjs state


【解决方案1】:

而不是这个:

this.state.id.push({"no" : length , "location": this.state.enteredlocation});

...做:

this.setState({ 
  id: this.state.id.concat({
    "no": length, 
    "location": this.state.enteredlocation
  })
});

这将确保id 是一个新的数组引用,而不是不同内容的同一个引用。

【讨论】:

  • 我见过人们使用Object.assign() 来组合新对象。使用concat有什么区别?
  • concat 对于数组来说更容易; Object.assign 是更新对象的好方法。或者使用传播(更简单):{ ...this.state.origObj, newProp: 'value' }
猜你喜欢
  • 2021-11-04
  • 2011-11-29
  • 2021-09-12
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多