我一直在使用 react.js 创建一个小应用程序。我过多地考虑了“性能”。
所以我有一个名为“Spinner”的简单子(monad)组件。我的目标是确保此组件永远不会重新呈现。
这是我的组件:
import React, {PureComponent} from 'react';
export default class Spinner extends PureComponent {
render() {
return (
<div className="spinner">
<div className="bounce1"></div>
<div className="bounce2"></div>
<div className="bounce3"></div>
</div>
)
}
}
在使用“react-addons-perf”重新渲染时,组件始终在渲染,我正在使用 PureComponent 因为我希望该组件只渲染一次,我读到我可以使用不可变 Prop 但是我不知道如何使这成为可能。
如果我这样做:
componentDidMount() {
this.renderState = false;
}
shouldComponentUpdate(nextProps, nextState) {
return (this.renderState === undefined) ? true : this.renderState;
}
它只渲染一次,但我相信有更好的方法。
如何避免重新渲染?或者我如何制作不可变 Prop ?
最佳答案
您不需要 componentShouldUpdate 的额外逻辑,因为您不希望您的组件重新呈现。
只添加这个应该足以防止组件重新渲染:
shouldComponentUpdate(nextProps, nextState) {
return false
}
关于javascript - 如何使 Prop 不可变以防止在 React 中重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41070202/