何时使用功能setState [英] When to use functional setState

查看:86
本文介绍了何时使用功能setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几天我一直在学习React,看几个教程和解释你可以编写不同元素的不同方式。然而,我最感兴趣的是 - setState 函数来更新/覆盖组件的状态属性。



例如,假设我有以下类:

  class Photos React.Component {
constructor(){
super()
state = {
pictures:[]
}
}

componentDidMount(){
//这是fetch和setState出现的位置(见下文)
}

render(){
return {
< div className =container>
{this.state.pictures}
< / div>





$ p
$ b

这个例子让我获取图像从一个API。

鉴于我已经执行了我的抓取,映射和返回这个函数 - 然后我会更新图片:[] 状态数组,并在API调用中获得结果。



我的问题源自我见过的关于如何更新/覆盖图片的不同方法国家财产。



我已经看到它以两种不同的方式写入:

1) strong> 这似乎是一个非常简单易读的方法

this.setState({pictures:pics })



2) 这是比较复杂的,但我认为它被描述为更安全方法

  this.setState(prevState =>({
pictures:prevState.pictures.concat (图片)
)))

有人可以解释一下使用的优点吗?我希望将来能够与代码保持一致,处理道具和状态等,所以最通用的方法当然是首选。 解决方案

第一件事情,首先,在你的情况下,这两种语法是完全不同的,你可能要寻找的是

  this.setState({pictures:this.state.picture.concat(pics)})

  this.setState(prevState =>({
pictures:prevState.pictures.concat(pics)
$ b))

为了理解为什么第二种方法是一种优先方法,您需要了解React在内部使用setState



React将首先将传递给 setState()的对象合并到当前状态。然后它会启动和解的事情。由于调用 setState()可能不会立即更新您的状态。



React可能会批量多次<$ c $



考虑一个简单的例子,为了理解这一点,在你可能调用的函数中setState不止一次像

  myFunction =()=> {

...
this.setState({pictures:this.state.picture.concat(pics1)})
this.setState({pictures:this.state。 picture.concat(pics1)})
this.setState({pictures:this.state.picture.concat(pics1)})

...
}

在简单应用程序中这不是有效的用例,但由于应用程序变得复杂,可能会发生多个setState调用来自多个地方,做同样的事情。 因此,现在为了执行有效的更新,React通过提取传递给每个 setState()调用,将它们合并在一起形成单个对象,然后使用该单个对象来执行 setState()。根据setState文档


如果您尝试在
相同的周期中多次增加一个项目数量,那将导致相当于:

  Object.assign(
previousState,
{quantity:state.quantity + 1 },
{quantity:state.quantity + 1},
...

后续调用将覆盖同一
周期内先前调用的值,因此数量只会增加一次。如果下一个
状态取决于之前的状态,我们建议使用更新程序
函数表单,而不是

因此,如果任何对象包含相同的密钥,则存储具有相同密钥的最后一个对象的密钥值。因此,更新只发生一次,最后一次值



Demo Codesandbox

I have been learning React over the past few days, looking at a few tutorials and explanations regarding the different ways in which you can write different elements. However there is one I have been most curious about - the setState function to update/override the state properties of a component.

For example, imagine I have a class with the following:

class Photos extends React.Component {
    constructor() {
        super()
        state = {
            pictures: []
        }
    }

   componentDidMount() {
      // This is where the fetch and setState will occur (see below)
   }

    render() {
       return {
          <div className="container">
             {this.state.pictures}
          </div>
       }
    }
}

This example sees me fetch images from an API.

Given that I have performed my fetch, map and return for this function - I will then update the pictures: [] state array with the results gained in the API call.

My question stems from the differing methods I have seen regarding how to update/override the pictures state property.

I have seen it written in 2 varying ways:

1) This seems to be a very simple and easy to read method

this.setState({pictures: pics})

2) This is more complex but I have see it described as a more safe method

this.setState(prevState => ({
   pictures: prevState.pictures.concat(pics)
}))

Could somebody please explain the merits of using either? I want to be consistent with code in the future, dealing with props and states etc, so the most versatile method would of course be preferred.

解决方案

First things first, in your case the two syntaxes are entirely different, what you might be looking for is the difference between

this.setState({pictures: this.state.picture.concat(pics)})

and

this.setState(prevState => ({
   pictures: prevState.pictures.concat(pics)
}))

To understand why the second method is a preffered one you need to understand what React does with setState internally

React will first merge the object you passed to setState() into the current state. Then it will start that reconciliation thing. Because of the Calling setState() might not immediately update your state.

React may batch multiple setState() calls into a single update for performance.

Consider the simple case, to understand this, in your function you might call setState more than once like

myFunction = () => {

   ...
   this.setState({pictures: this.state.picture.concat(pics1)})
   this.setState({pictures: this.state.picture.concat(pics1)})
   this.setState({pictures: this.state.picture.concat(pics1)})

   ...
}

which isn't a valid usecase in a simple app but as the app gets complex, multiple setState calls may be happening from multiple places, doing the same thing.

So now to perform an efficient update, React does the batching thing by extracting all the objects passed to each setState() call, merges them together to form a single object, then uses that single object to do setState(). According to setState documentation

If you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:

Object.assign(
  previousState,
  {quantity: state.quantity + 1},
  {quantity: state.quantity + 1},
  ...
)

Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the previous state, we recommend using the updater function form, instead

So if any of the objects contains the same key, the value of the key of the last object with same key is stored. And hence the update only happens once with the last value

Demo Codesandbox

这篇关于何时使用功能setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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