setState()
函数是做什么的?它只会运行render()
函数吗?
setState()
函数会运行什么?它只运行render()
吗?
不是的,setState不仅调用render()
函数,而且在setState
之后,以下生命周期函数将按顺序运行,具体取决于shouldComponentUpdate
返回的结果。
如果shouldComponentUpdate
返回true(默认为true)。
1. shouldComponentUpdate
2. componentWillUpdate
3. render()
4. componentDidUpdate
shouldComponentUpdate
返回false
1. shouldComponentUpdate
关于setState,还有一件事需要知道,它只会触发当前组件及其所有子组件的重新渲染(假设没有任何子组件实现shouldComponentUpdate),它不会触发父组件的重新渲染,因此父组件不会进行协调,而仅对自身和其子组件进行协调。
下面是一个调用setState时发生的DEMO。
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'));
<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>
为了回答@poepje在您的问题中提出的疑问,需要添加解释。
setState是什么?
setState()将更改排队到组件状态,并告诉React需要使用更新后的状态重新渲染此组件及其子组件。这是您用于响应事件处理程序和服务器响应来更新用户界面的主要方法。
React在此功能文档中有很好的说明。
您也可以查看以下答案,了解setState的工作原理:
setState() 将按照以下顺序运行函数:
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
如果您的组件正在接收 props,则将使用上述函数运行 componentWillRecieveProps()
函数。
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
这是对答案的更新: https://dev59.com/HFcO5IYBdhLWcg3ww0Vt#45273993 (因为现在生命周期方法已经更新)
setState() 将按照以下顺序运行函数:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapBeforeUpdate
(如果存在)
componentDidUpdate()
根据此文档: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
react-dom
的函数,这些函数实际上进行了差异化和DOM更新(如果需要)。 - marzelin