调用setState()函数时会发生什么?

16 javascript reactjs

setState()功能运行的是什么?它只运行render()吗?

Shu*_*tri 27

setState()功能运行的是什么?它只运行吗render()

没有 setState不仅调用render()函数,而且之后setState,以下生命周期函数将按顺序运行,具体取决于shouldComponentUpdate返回的内容

if shouldComponentUpdate返回true(默认为true).

1. shouldComponentUpdate
2. componentWillUpdate
3. render()
4. componentDidUpdate
Run Code Online (Sandbox Code Playgroud)

if shouldComponentUpdate返回false(如果你有自定义实现)

1. shouldComponentUpdate
Run Code Online (Sandbox Code Playgroud)

关于setState的另一件事是,它只触发当前组件及其所有子组件的重新呈现(考虑shouldComponentUpdate到它的任何子组件都没有实现),它不会触发父组件的重新呈现因此,reconcilation父组件不会发生这种情况,但仅适用于其自身及其子组件.

setState调用时发生的事情的演示.

class App extends React.Component {
    state = {
      count: 0
    }
    componentWillReceiveProps(nextProps) {
       console.log('componentWillReceiveProps parent');
    }
    shouldComponentUpdate() {
      console.log('shouldComponentUpdate parent');
      return true;
    }
    componentWillUpdate() {
      console.log('componentWillUpdate parent');
    }
    render() {
      console.log('render parent')
      return (
        <div>
            <Child count = {this.state.count}/>
            <button onClick={() => {
            console.log('callingsetState');this.setState((prevState) => ({count: prevState.count + 1}))}} >Increase</button>
        </div>
      )
    }
    componentDidUpdate() {
      console.log('componentDidUpdate parent')
    }
}
class Child extends React.Component {
    
    componentWillMount() {
      console.log('componentWillMount child');
    }
    componentDidMount() {
      console.log('componentDidMount child');
    }
    componentWillReceiveProps(nextProps) {
       console.log('componentWillReceiveProps child');
    }
    shouldComponentUpdate() {
      console.log('shouldComponentUpdate child');
      return true;
    }
    componentWillUpdate() {
      console.log('componentWillUpdate child');
    }
    render() {
      console.log('child')
      return (
        <div>
            <div>{this.props.count}</div>
        </div>
      )
    }
    componentDidUpdate() {
      console.log('componentDidUpdate child')
    }
}


ReactDOM.render(<App/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

为@poepje在您的问题上添加的问题添加解释

setState有什么作用?

setState()将对组件状态的更改排入队列,并告诉React需要使用更新后的状态重新呈现此组件及其子组件.这是用于更新用户界面以响应事件处理程序和服务器响应的主要方法.

React在这里有关于此功能的非常好的文档

您还可以看到有关setState如何工作的以下答案:

setState不会立即更新状态


小智 10

setState()将按以下顺序运行函数:

shouldComponentUpdate()

componentWillUpdate()

render()

componentDidUpdate()

如果您的组件正在接收道具,它将运行componentWillRecieveProps()具有上述功能的功能.