我有一个非常简单的组件,因为我记录信息以检查组件生命周期,并看到构造函数和呈现函数在每次重新加载浏览器时都被调用两次。有人能帮我复习一下为什么吗?
这是我的代码,以及图片中的结果。
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'Viet'
};
console.log('App constructor');
}
componentWillMount() {
console.log('App componentWillMount');
}
componentDidMount() {
console.log('App componentDidMount');
}
changeState = () => {
this.setState({ name: 'Viet is changed' })
}
render() {
console.log('App render');
return (
<div className='App'>
{this.state.name}
{<button onClick={this.changeState.bind(this)} >Click to change state</button>}
</div>
);
}
}
export default App;

发布于 2020-03-25 17:53:39
在您的render方法中,您没有正确地传递函数,这是因为重新呈现了哪个组件。您需要在构造函数中绑定该函数,将按钮的onClick更改为:
constructor(props) {
super(props);
this.state = {
name: 'Viet'
};
console.log('App constructor');
this.changeState = this.changeState.bind(this);
}
<button onClick={this.changeState}>Click to change state</button>发布于 2020-08-08 13:10:47
双重渲染是由React.StrictMode造成的。如果你检查你的src/index.js,应用组件是用React.StrictMode标签包装的。
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);在发布说明中提到的:"React.StrictMode是一个帮助为异步渲染准备应用程序的包装器“。
附言:重新渲染没什么好担心的。
https://stackoverflow.com/questions/60846339
复制相似问题