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

时间:2022-06-17 13:28:34

I was working with React JS and I was wondering the difference between calling setState() twice to set two different state variables like this:

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

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

AND

calling setState() once and passing both state variables as JSON like this:

调用setState()一次并将这两个状态变量作为JSON传递:

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

Also what is the better practice: putting state variable names in double quotes like this: this.setState({"fruit1": “apple”}) or simply ignoring the quotes?

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

3 个解决方案

#1


Inside a React event handler (that is, a function called from a React-based onChange={...} property and the like), multiple calls to setState are batched and the component is only re-rendered a single time. So, there's no difference between

在React事件处理程序内部(即,从基于React的onChange = {...}属性调用的函数等)中,对setState的多次调用进行批处理,并且组件仅重新呈现一次。所以,两者之间没有区别

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

and

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

However, outside of the React event system, the two calls to setState will not be merged unless you wrap them in a function passed to React.addons.batchedUpdates. This is normally not something you have to worry about, but may become an issue if you start setting state in response to asynchronous events (e.g. timers, promises, callbacks, etc). For that reason, I would generally recommend the second form (with the two objects merged into one) over the first.

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

#2


From React documentation:

来自React文档:

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.state,因为之后调用setState()可能会替换你所做的突变。把this.state看作是不可变的。 setState()不会立即改变this.state,但会创建挂起状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以提高性能。除非在shouldComponentUpdate()中实现条件呈现逻辑,否则setState()将始终触发重新呈现。如果正在使用可变对象并且无法在shouldComponentUpdate()中实现逻辑,则仅当新状态与先前状态不同时调用setState()将避免不必要的重新呈现。

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

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

For the second question you can look here and here

对于第二个问题,你可以在这里和这里看看

#3


Here is a detailed explanation of React States and setState() method.

以下是React States和setState()方法的详细说明。

States (and props) are only two reasons why React re-renders/recalculate the DOM. It means if we change State, we are telling react to change the related behaviour of our app.

状态(和道具)只是React重新渲染/重新计算DOM的两个原因。这意味着如果我们改变状态,我们就会做出反应来改变我们应用的相关行为。

State is a Java-Script object with key:value pair. Now we may have many States (many key:value pairs) and let's say at certain point only one state is changing. in that case we may use this.setState() method to change only that specific state.

State是一个带有键:值对的Java脚本对象。现在我们可能有许多国家(许多关键:价值对),让我们说在某些时候只有一个国家正在发生变化。在这种情况下,我们可以使用this.setState()方法仅更改该特定状态。

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

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

let's say we want to update fruit1: 'watermelon'.

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

Here we can say:

在这里我们可以说:

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

Here, we did not say anything about second state (fruit2), so react will merge changed state (fruit1) with old state (fruit2).

在这里,我们没有说出关于第二个状态(fruit2)的任何内容,因此react会将更改状态(fruit1)与旧状态(fruit2)合并。

While, we can also say:

虽然,我们也可以说:

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

But it is not necessary.

但这没有必要。

Correct and Re-commanded way of setting/changing State:

正确和重新命令设置/更改状态的方式:

From React Official docs:

来自React官方文档:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

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

So here is a better way to do it: If we are updating the counter or calculating something:

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

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

#1


Inside a React event handler (that is, a function called from a React-based onChange={...} property and the like), multiple calls to setState are batched and the component is only re-rendered a single time. So, there's no difference between

在React事件处理程序内部(即,从基于React的onChange = {...}属性调用的函数等)中,对setState的多次调用进行批处理,并且组件仅重新呈现一次。所以,两者之间没有区别

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

and

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

However, outside of the React event system, the two calls to setState will not be merged unless you wrap them in a function passed to React.addons.batchedUpdates. This is normally not something you have to worry about, but may become an issue if you start setting state in response to asynchronous events (e.g. timers, promises, callbacks, etc). For that reason, I would generally recommend the second form (with the two objects merged into one) over the first.

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

#2


From React documentation:

来自React文档:

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.state,因为之后调用setState()可能会替换你所做的突变。把this.state看作是不可变的。 setState()不会立即改变this.state,但会创建挂起状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以提高性能。除非在shouldComponentUpdate()中实现条件呈现逻辑,否则setState()将始终触发重新呈现。如果正在使用可变对象并且无法在shouldComponentUpdate()中实现逻辑,则仅当新状态与先前状态不同时调用setState()将避免不必要的重新呈现。

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

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

For the second question you can look here and here

对于第二个问题,你可以在这里和这里看看

#3


Here is a detailed explanation of React States and setState() method.

以下是React States和setState()方法的详细说明。

States (and props) are only two reasons why React re-renders/recalculate the DOM. It means if we change State, we are telling react to change the related behaviour of our app.

状态(和道具)只是React重新渲染/重新计算DOM的两个原因。这意味着如果我们改变状态,我们就会做出反应来改变我们应用的相关行为。

State is a Java-Script object with key:value pair. Now we may have many States (many key:value pairs) and let's say at certain point only one state is changing. in that case we may use this.setState() method to change only that specific state.

State是一个带有键:值对的Java脚本对象。现在我们可能有许多国家(许多关键:价值对),让我们说在某些时候只有一个国家正在发生变化。在这种情况下,我们可以使用this.setState()方法仅更改该特定状态。

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

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

let's say we want to update fruit1: 'watermelon'.

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

Here we can say:

在这里我们可以说:

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

Here, we did not say anything about second state (fruit2), so react will merge changed state (fruit1) with old state (fruit2).

在这里,我们没有说出关于第二个状态(fruit2)的任何内容,因此react会将更改状态(fruit1)与旧状态(fruit2)合并。

While, we can also say:

虽然,我们也可以说:

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

But it is not necessary.

但这没有必要。

Correct and Re-commanded way of setting/changing State:

正确和重新命令设置/更改状态的方式:

From React Official docs:

来自React官方文档:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

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

So here is a better way to do it: If we are updating the counter or calculating something:

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

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