【问题标题】:how to stop re-render in reactjs?如何停止在reactjs中重新渲染?
【发布时间】:2018-07-20 11:22:04
【问题描述】:

 case 'splitWord': 
            if(this.props.remedStatus){
                console.log(this.props.remedStatus)
                console.log("remed")
                return(
                   <HotspotRemed 
                        xml={this.receivedXML}
                        userXml={this.usersAnswerXML}
                        correctAnswer ={this.ansString}
                        type={this.splitType}
                    />
                ) 
            } else {
                console.log("reurn word")
                return(
                    
                    <div style ={wrap_style} >
                    {this.forceUpdate}
                        <SplitXMLPreview xml={this.receivedXML}
                            type='w' 
                            assignedSplitContentClick={(contentId, selectionType) => {
                                this.handleSplitContentClick(contentId, selectionType, 'w')
                            }}
                            getCorrectAns={(answers) => {
                                this.correctAnswers = answers
                            }}
                        />
                    </div>
                )
            }
           
            break
            
            
            <<<==NOW HERE IS MY RENDER MEHTOD.==>>>
            
                render() {
        console.log("render")
            return (
                <div className="previewtemplate" style ={template}>
                    {this.templateArea(this.state.templateType)}
                </div>
            );
        
    }
}
            
            

我只是想知道如何停止重新渲染组件。

当我点击一个按钮时,我有三个按钮,它会在那里执行操作。

只有一个按钮。我在其中使用 if else 当我单击该按钮时,它返回 false 和组件 false 调用,这很好,当再次单击该按钮时,它调用 true 组件,这对我来说也很好,但是当我再次单击按钮时首先它调用渲染然后调用我的组件。我不想调用渲染它调用我的组件。

我阅读了一些他们建议使用 this.forceupdate 的博客。 我该怎么办?帮帮我。

【问题讨论】:

  • 如果状态没有改变,React 组件不应该重新渲染。每次点击都调用 this.setState({}) 吗?
  • 是的,我改变了状态。

标签: javascript reactjs render rerender


【解决方案1】:

您可以使用shouldComponentUpdate 方法实现确定组件是否应更新(重新渲染)的自定义逻辑。

例如:

shouldComponentUpdate () {
    return false // this will lead to never re-render the component
}

请注意,未来 React 可能会将 shouldComponentUpdate() 视为提示而不是严格指令,返回 false 仍可能导致组件重新渲染。

Here is a deeper explanation 来自文档。

【讨论】:

  • 我想在不需要停止初始化时停止渲染。当我使用 shouldComponentUpdate 时,它​​只渲染一次。有什么方法可以在我需要时停止渲染方法。
猜你喜欢
  • 1970-01-01
  • 2016-05-26
  • 2016-07-26
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多