javascript - 如何在 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})
}
}
但是我的代码陷入了无限循环。我该如何解决?欢迎任何其他解决方案。
解决方案
如果您想存储一个值但不让组件在该值更改时重新呈现,则它不应该处于该状态。它应该只是一个实例变量,例如
constructor(props, context) {
this.ShowVoucher = false;
}
接着
this.ShowVoucher = true;
不要将事物置于状态,然后尝试阻止它们的更改导致重新渲染。这是一种反模式。
推荐阅读
- python - 循环或递归
- actionscript-3 - 使用 Adobe Animate CC 发布具有 API 26 目标的应用程序,但从 Google Play 控制台收到错误消息,目标是 API 24
- reactjs - 如何使用 enter 提交语义反应搜索
- css - 如何在 flexbox 容器中有方形大小的元素?
- reactjs - 存储加载后更新组件,使用选择器
- flutter - 凡士通离线能力扑朔迷离
- html - 如果布尔值为false,Angular 4 typescript会禁用按钮吗?
- java - Golang 与 Java 的速度
- java - Java 图像面板文件导入
- twitter-bootstrap - 当内容更宽时,如何将引导导航栏修复到视口?