简体   繁体   English

state 更新如何合并到 React 挂钩中?

[英]How state updates merge in React hooks?

Will react merge the state updates for hooks too, like it does for setState也会对钩子的 state 更新做出反应,就像对setState所做的那样

    state={count:0}  
  
    increment = () => {
    this.setState({count: this.state.count+1})
    this.setState({count: this.state.count+2})
    }

In Class component, the last setState action will be taken into consideration.Since the state updates are shallow merged .在 Class 组件中,将考虑最后的setState操作。由于 state 更新是浅合并的。

When you call setState(), React merges the object you provide into the current state.The merging is shallow.当你调用 setState() 时,React 将你提供的 object 合并到当前的 state 中。合并是浅的。

Object.assign(
    {},
    {count: this.state.count+1},
    {count: this.state.count+2}
)

the final result will be state = {count: 2}最终结果将是state = {count: 2}

In functional component,在功能组件中,

const [count,setCount] = useState(0)

const increment = () => {
    setCount(count+1)
    setCount(count+2)
}

The result is same as Class component count = 2 .结果与 Class 组件count = 2相同。

Does setCount in useState hook will behave the same as setState ?, Will setCount(count+1) ever execute? setCount钩子中的 setCount 的行为是否与setState相同? setCount(count+1)会执行吗?

Its not true what you state here:您在这里的 state 不是真的:

"In Class component, the last setState action will be taken into consideration. Since the state updates are shallow merged. ". “在 Class 组件中,将考虑最后一个 setState 操作。由于 state 更新是浅合并的。 ”。

Same goes for your example with Object.assign .您的示例Object.assign

The "merge" mentioned in React docs is related to merging with current state, for example: React 文档中提到的“合并”与与当前 state 合并有关,例如:

state = { count: 0, name: 'Dennis' }

// Merged with this.state, the 'name' attribute is not removed
this.setState({count: this.state.count+1})

// the state now is { count: 1, name: 'Dennis' }

While same code, won't work with function component, since its different API, as mentioned in the docs, it doesn't merge.虽然相同的代码,但不能与 function 组件一起使用,因为它的 API 不同,如文档中所述,它不会合并。

const [state,setState] = useState({ count: 0, name: 'Dennis' })

// NO MERGE, you assign a new object
setState({count: state.count+1})

// the state now is { count: 1 }

Therefore, asking if the "setState call ever execute" is not related to class / function component, its a matter if the set state call is batched or not.因此,询问“setState call ever execute”是否与 class / function 组件无关,这是设置 state 调用是否被批处理的问题。

Does setCount in useState hook will behave the same as setState?, Will setCount(count+1) ever execute? useState 钩子中的 setCount 的行为是否与 setState 相同? setCount(count+1) 会执行吗?

If the calls don't batch, the first call will be executed.如果调用不批处理,将执行第一个调用。

When set state calls are batched?当设置 state 调用被批处理? See here .这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM