javascript – 调用setState()函数时会发生什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 调用setState()函数时会发生什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2513字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 调用setState()函数时会发生什么?](/upload/InfoBanner/zyjiaocheng/710/94d78a7bb43943b091ff4b66b2a3d9c7.jpg)
setState()函数运行的是什么?它只运行render()吗?
解决方法:
What does the
setState()
function run? Does it only runrender()
没有setState不仅调用render()函数,而且在setState之后,以下生命周期函数将按顺序运行,具体取决于shouldComponentUpdate返回的内容
if shouldComponentUpdate返回true(默认为true).
1. shouldComponentUpdate
2. componentWillUpdate
3. render()
4. componentDidUpdate
if shouldComponentUpdate返回false(如果您有自定义实现)
1. shouldComponentUpdate
关于setState的另一件事是,它只触发当前组件及其所有子组件的重新呈现(考虑到没有为任何子组件实现shouldComponentUpdate),它不会触发父组件的重新呈现组件因此,父组件不会发生协调,而只会为其自身及其子组件进行协调.
调用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'));
<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() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the
updated state. This is the primary method you use to update the user
interface in response to event handlers and server responses.
React有关于此功能here的非常好的文档
您还可以看到有关setState如何工作的以下答案:
setState doesn’t update the state immediately
内容总结
以上是互联网集市为您收集整理的javascript – 调用setState()函数时会发生什么?全部内容,希望文章能够帮你解决javascript – 调用setState()函数时会发生什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。