代码之家  ›  专栏  ›  技术社区  ›  Boris Grunwald

这是一个使用shouldComponentUpdate生命周期方法的好地方吗?(RACTJS)

  •  0
  • Boris Grunwald  · 技术社区  · 6 年前

    我正在学习如何做出一个简单的游戏。在这个游戏中,我有一个容器组件来管理倒计时。当玩家开始游戏时,我运行以下功能:

    startTimer = () => {
        setInterval(() => {
            this.setState((prevState) => ({
                timeLeft:prevState.timeLeft-1
            }))
        },1000)
    };
    

    我的容器组件具有以下呈现方法:

    render() {
    
    
        return (
            <div className="container">
                <GameStats
                    gameStarted={this.state.gameStarted}
                    question={this.state.question}
                    numOfQuestions={this.state.numOfQuestions}
                    correctAnswers={this.state.correctAnswers}
                    timeLeft={this.state.timeLeft}
                />
                <Board
                    gameStarted={this.state.gameStarted}
                    startGame={this.startGame}
                    squareClicked={this.squareClickedHandler}
                    sqOne={this.state.squareOne}
                    sqTwo={this.state.squareTwo}
                    sqThree={this.state.squareThree}
                    sqFour={this.state.squareFour}
                />
            </div>
        )
    }
    

    gamestats组件负责渲染剩余时间,而board组件不使用剩余时间。因此,将Board组件转换为基于类的组件并实现ShouldComponentUpdate挂钩,这样它就不会每秒重新发送一次了,这是否有意义?

    1 回复  |  直到 6 年前
        1
  •  0
  •   alex-k    6 年前

    是的,一般情况下,您应该尽量避免更新 Board 每次时钟滴答滴答时,组件。最好是把你的 董事会 组件到 PureComponent .

    如中所述 docs 纯组分 已经实现 shouldComponentUpdate :

    react.purecomponent与react.component类似。它们之间的区别在于react.component不实现shouldComponentUpdate(),但是react.purecomponent通过一个简单的属性和状态比较来实现它。

    确保您在文档中进一步阅读了浅层比较的警告。