簡體   English   中英

分布在反應的setState中

[英]spread in setState of react

我在某個地方看到了這個,我很困惑。 我從來沒有這樣做過,實際上它是做什么的?

doSomething = index => {
    const tempState = this.state
    tempState.keys.push(index)

    this.setState({
      ...tempState
    })
  }
const tempState = this.state

上面為tempState分配了對狀態對象的引用

tempState.keys.push(index)

tempState具有鍵的屬性,該屬性保存對數組的引用,並在數組上調用push以向數組添加index

this.setState({
  ...tempState
})

this.setState並將狀態的新副本傳遞到setState 傳播運算符基本上是將舊狀態的內容復制到新對象中。

上面的實現不是完美的實現,應該對其進行改進,以免改變原始狀態對象。

doSomething = index => {
    const tempState = this.state  // assing reference of state to tempState
    tempState.keys.push(index) // push a value to `keys` property value within state. Note that Javascript object assignment works by reference and hence this will actually mutate the state object

    this.setState({ 
      ...tempState
    }) // call setState to update state and pass the cloned version of tempState using spread syntax as the new state values
  }

盡管上述實現在setState之前克隆了該值,但它是不正確的,因為它應該在對其進行任何更新之前克隆該值

doSomething = index => {
    const keys = [...this.state.keys]
    keys.push(index)

    this.setState({
      keys
    })
  }

但是,由於您使用ES5,因此為了克隆值,可以使用concat使用setState之類的功能來更新鍵數組。

doSomething = index => {

    this.setState(prevState => ({
      keys: prevState.keys.concat([index])
    }))
  }

希望以上答案能為您提供所需的解釋的見解

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM