简体   繁体   English

state 在 shouldComponentUpdate 之后和渲染之前是否得到更新

[英]Does state get updated after shouldComponentUpdate and before render

I'm new to React, just a question on how component's state object get updated.我是 React 的新手,只是关于如何更新组件的 state object 的问题。 After analyzing some code, I think:在分析了一些代码后,我认为:

In update phase, state get updated after shouldComponentUpdate method but before render method, is my understanding correct?在更新阶段,state 在 shouldComponentUpdate 方法之后但在 render 方法之前得到更新,我的理解是否正确?

If the answer is yes, is it another dedicated method(sth like "UpdatingState") to updated the state object?如果答案是肯定的,是否是另一种专用方法(例如“UpdatingState”)来更新 state object?

updating state in react is done through the setState lifecycle method在 react 中更新 state 是通过setState生命周期方法完成的

you can call it like this this.setState({name: 'new name'}) this updates the state object key name to be the new value, in this case new name您可以这样称呼它this.setState({name: 'new name'})这会将 state object 键name更新为新值,在本例中new name

updating objects is a little bit harder.更新对象有点困难。 you have to first clone the object.你必须先克隆 object。 then change the value then reset the state like so然后更改值,然后像这样重置 state

state = {
   person: {
     name: 'peter',
     age: 25
}

const copy = {...this.state.person}
copy.name = 'new name'
this.setState({copy})

Yes, the state will be updated ( setState ) after shouldComponentUpdate.是的,state 将在 shouldComponentUpdate 之后更新 ( setState )。 The order of update phase would be更新阶段的顺序是

  1. getDerivedStateFromProps getDerivedStateFromProps
  2. shouldComponentUpdate应该组件更新
  3. render使成为
  4. componentDidUpdate组件DidUpdate

to update state use setState更新 state 使用setState

there is a function that is called after each update in state and props:在 state 和道具中的每次更新后都会调用一个 function :

componentDidUpdate(prevProps , prevState)

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

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