reactjs - React 类组件:为什么它不会导致重新渲染?
问题描述
为什么即使状态改变,下面的代码也不会导致重新渲染?
constructor(props) {
super(props);
this.state = {
counter: 1
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(previousState => {this.state.counter = previousState.counter + 1},()=>{
console.log(this.state.counter)
});
}
但这有效......因为我正在改变 this.state.counter??
constructor(props) {
super(props);
this.state = {
counter: 1
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(previousState => {this.state.counter = previousState.counter + 1},()=>{
console.log(this.state.counter)
});
}
我知道较短的代码:
handleClick = () =>{
this.setState({counter : this.state.counter + 1})
}
解决方案
使用以下方式设置状态:
this.setState(previousState => { this.state.counter = previousState.counter + 1 })
将直接修改 React 状态,应该避免这种情况并可能导致意外的副作用(如组件未重新渲染)。
您似乎正在尝试做的事情(根据以前的状态修改状态),应该这样做:
this.setState(previous => ({ counter: previous.counter + 1 }))
// Or
this.setState(previous => { return { counter: previous.counter + 1 } })
它返回更改,因此 React 可以感知更改并异步处理它,而不是在 Reacts 控制之外自己修改它。
推荐阅读
- r - 构建遍历列的函数
- asp.net - 在 aspnet 核心中使用策略覆盖 AuthorizeAttribute
- php - Symfony:项目创建
- javascript - Python mkdir() '没有这样的文件或目录' w/ NodeJS
- r - 在现有 geo_histogram 中添加 geom_freqpoly
- python - 我的 Discord.py 调平系统问题 - 传奇
- apache-kafka - 同步Kafka生产者是否有任何例外
- jersey - 类型 javax.ws.rs.core.Form 的 Resteasy 抛出错误 RESTEASY003215
- azure-active-directory - 测试 - Azure AD 是否支持 ABAC(基于属性的访问控制)?
- rust - 关联类型的等式约束的替代方法