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

我一直在使用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>
    )
}

}

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

如果我做一些喜欢这个:

componentDidMount() {
    this.renderState = false;
}

shouldComponentUpdate(nextProps,nextState) {
    return (this.renderState === undefined) ? true : this.renderState;
}

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

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

解决方法

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

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

shouldComponentUpdate(nextProps,nextState) {
    return false
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...