如何使道具不可变,以防止在React中重新渲染?

Jed*_*ias 6 javascript performance reactjs

我一直在使用react.js创建一个小应用程序.我过分考虑了"表现".

所以我有一个名为"Spinner"的简单子组件.我的目标是确保此组件永远不会重新呈现.

这是我的组件:

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>
    )
}

}
Run Code Online (Sandbox Code Playgroud)

在使用'react-addons-perf'重新渲染时,组件总是渲染,我使用的是PureComponent,因为我希望该组件只渲染一次,我读到我可以使用不可变的道具,但我不知道我知道如何使这成为可能.

如果我做一些喜欢这个:

componentDidMount() {
    this.renderState = false;
}

shouldComponentUpdate(nextProps, nextState) {
    return (this.renderState === undefined) ? true : this.renderState;
}
Run Code Online (Sandbox Code Playgroud)

它只呈现一次,但我相信有更好的方法.

如何避免重新渲染?或者我怎么能制作不变的道具?

Fur*_*anO 7

您不需要为componentShouldUpdate提供额外的逻辑,因为您不希望您的组件永远重新渲染.

仅添加此项应足以防止组件重新呈现:

shouldComponentUpdate(nextProps, nextState) {
    return false
}
Run Code Online (Sandbox Code Playgroud)