作者:210213银成弘19952_Q8S | 来源:互联网 | 2023-01-28 17:17
该setState()
功能运行的是什么?它只运行render()
吗?
1> Shubham Khat..:
该setState()
功能运行的是什么?它只运行吗render()
没有 setState不仅调用render()
函数,而且之后setState
,以下生命周期函数将按顺序运行,具体取决于shouldComponentUpdate
返回的内容
if shouldComponentUpdate
返回true(默认为true).
1. shouldComponentUpdate
2. componentWillUpdate
3. render()
4. componentDidUpdate
if shouldComponentUpdate
返回false(如果你有自定义实现)
1. shouldComponentUpdate
关于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 (
)
}
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 (
)
}
componentDidUpdate() {
console.log('componentDidUpdate child')
}
}
ReactDOM.render(, document.getElementById('app'));
2> 小智..:
setState()将按以下顺序运行函数:
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
如果您的组件正在接收道具,它将运行componentWillRecieveProps()
具有上述功能的功能.