当我单击按钮时,我在控制台中看到“1”,但从未看到“2”。为什么会这样?你能帮我解决这个问题吗?我真的不知道为什么我的第二个组件没有更新。
class App extends PureComponent {
constructor() {
super();
this.state = {
name: 'Vasya'
}
this._onChange = this._onChange.bind(this);
}
_onChange(name) {
this.setState({
name: name
});
}
render() {
console.log(1);
return {
<div>
<Button onClick={this._onChange('Petr')} />
<AnotherComponent username={this.state.name} />
</div>
}
}
}
class AnotherComponent extends PureComponent {
const {
username
} = this.props
render() {
console.log(2);
return {
<div>
test
</div>
}
}
}
export default App;
最佳答案
您的示例中存在一些代码问题!
- 当您从 render() 返回 React 元素时,它们必须用括号 () 包裹,而不是 curl {}
- 使用 React.Component,而不是 React.PureComponent,否则你会遇到问题
然后主要的问题是无限循环 - 当你渲染时,这一行:
<Button onClick={this._onChange('Petr')} />
...这会在渲染时调用 _onChange() 函数并将结果作为 onClick 属性传递给 Button。这不是您想要的 - 您希望 onClick 属性成为调用 _onChange() 的函数。所以
<button onClick={ () => this._onChange('Petr')} />
完整的工作示例:
class App extends React.Component {
constructor() {
super();
this.state = {
name: 'Vasya'
}
this._onChange = this._onChange.bind(this);
}
_onChange(name) {
this.setState({
name: name
});
}
render() {
console.log(1);
return (
<div>
<button onClick={ () => this._onChange("Petr") } />
<AnotherComponent username={this.state.name} />
</div>
);
}
}
class AnotherComponent extends React.Component {
render() {
console.log(2);
return (
<div>
test
</div>
);
}
}
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>
关于javascript - 我的组件没有重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46084019/