class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: 'click button',
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happen');
this.setState({});
}
render() {
console.log('App render');
const { message } = this.state;
return (
<button onClick={ this.handleClick }>{ message }</button>
);
}
}
如上代码,如果点击按钮的话, 输出内容是
Click happen
App render
App render
为什么render函数会执行两次呢?
找到原因了,是因为我的用例是直接通过create-react-app模式创建的,默认就是StrictMode下。StrticMode默认会执行两次render,来检测你的render函数有没有副作用。https://stackoverflow.com/que...