首页 > 解决方案 > 如何在 React js 中使用 setstate 而不重新渲染组件?

问题描述

constructor(props, context) {
super(props);
this.state = {
ShowVoucher: false
 }

我想改变showVoucher的状态。无需重新渲染组件。我试过这样

componentDidUpdate(prevState) {
if(prevState.showVoucher!= this.state.showVoucher){
  this.setState({ ShowVoucher: false})
}
  }

但是我的代码陷入了无限循环。我该如何解决?欢迎任何其他解决方案。

标签: javascriptreactjs

解决方案


如果您想存储一个值但不让组件在该值更改时重新呈现,则它不应该处于该状态。它应该只是一个实例变量,例如

constructor(props, context) {
    this.ShowVoucher = false;
}

接着

this.ShowVoucher = true;

不要将事物置于状态,然后尝试阻止它们的更改导致重新渲染。这是一种反模式。


推荐阅读