问题
连续两次setState会渲染几次?
回答
一次
React 可以将多个setState() 调用合并成一个调用来提高性能
实例
假设有一个组件:
import React from 'react';
export default class TestState extends React.Component {
constructor () {
super();
this.state = {
name: 'null',
age: 0,
}
}
changeState = () => {
this.setState({ name: 'Zhang' });
this.setState({ age: 18 });
}
render () {
console.log(`界面开始渲染, name: ${this.state.name}, age: ${this.state.age}`);
return <div>
<div>My name is {this.state.name}, age is {this.state.age}</div>
<button onClick={this.changeState}>Click</button>
</div>
}
}
![b0a6484867fb4e0e7ca34568f6f7127d.gif](https://i-blog.csdnimg.cn/blog_migrate/7f768d62f8e9c8aaa90489567dc5a60a.gif)