在 Reactjs 中设置状态变量的正确方法是什么?这些方法之间有什么区别?

What is the correct way of setting state variables in Reactjs and what is the difference between these approaches?

我正在使用 React JS,我想知道两次调用 setState() 来设置两个不同的状态变量之间的区别,如下所示:

this.setState({fruit1: “apple”});
this.setState({fruit2: “mango”});

调用 setState() 一次并将两个状态变量作为 JSON 传递,如下所示:

this.setState({fruit1: “apple”, fruit2: “mango”});

此外,更好的做法是什么:将状态变量名称放在双引号中,如下所示:this.setState({"fruit1": “apple”}) 或干脆忽略引号?

来自React documentation

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable. setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

所以,使用 this.setState({fruit1: “apple”, fruit2: “mango”});

第二个问题可以看here and here

在 React 事件处理程序中(即从基于 React 的 onChange={...} 属性 等调用的函数),对 setState 的多次调用是批处理的,组件只重新渲染一次。所以,

之间没有区别
handleClick: function() {
  this.setState({fruit1: "apple"});
  this.setState({fruit2: "mango"});
}

handleClick: function() {
  this.setState({fruit1: "apple", fruit2: "mango"});
}

但是,在 React 事件系统之外,对 setState 的两次调用将不会合并,除非您将它们包装在传递给 [=15= 的函数中].这通常不是您必须担心的事情,但如果您开始设置状态以响应异步事件(例如计时器、承诺、回调等),则可能会成为一个问题。出于这个原因,我通常会推荐第二种形式(将两个对象合并为一个)而不是第一种形式。

这里详细解释了 React States 和 setState() 方法。

States(和 props)只是 React re-renders/recalculate DOM 的两个原因。这意味着如果我们改变 State,我们会告诉 React 改变我们应用程序的相关行为。

State 是一个 Java-Script 对象,带有 key:value 对。现在我们可能有很多状态(很多 key:value 对),假设在某个时刻只有一个状态在变化。在那种情况下,我们可以使用 this.setState() 方法来仅更改该特定状态。

state = { fruit1: 'mango', fruit2: 'apple' }

假设我们要更新 fruit1:'watermelon'。

这里我们可以说:

this.setState( {fruit1: 'watermelon'} ); 

在这里,我们没有提到第二个状态 (fruit2),所以 React 会将更改后的状态 (fruit1) 与旧状态 (fruit2) 合并。

虽然,我们也可以说:

this.setState( {fruit1: 'watermelon' ,fruit2:'apple'} ); 

但是没有必要。

setting/changing状态的正确和重新命令方式:

来自 React 官方文档:

将 setState() 视为请求而不是更新组件的即时命令。为了更好地感知性能,React 可能会延迟它,然后在一次传递中更新多个组件。 React 不保证状态更改会立即应用。

所以这是一个更好的方法: 如果我们正在更新计数器或计算一些东西:

this.setState((prevState,props) => {
 return {
           { counter: prevState.counter+1; }
        }