簡體   English   中英

如何防止在 React.js 中重新渲染父組件

[英]How prevent rerender of parent component in React.js

我有一個組件 ProductList - 它是一個父組件。 在 m 渲染方法中我寫了這樣的代碼

 return (
        <div>
            <CustomBreadCrumbs routes={this.props.routes} params={this.props.params} />
            { this.props.children ? this.props.children :
                <section className="content">
                    Parent
                </section>
            }
        </div>
    );

當我在子組件中編輯一些信息時,我的父組件會重新渲染,但我想阻止它。 我該怎么做?

這是不可能的,因為只有在重新渲染父組件時才會調用子組件的重新渲染。

正如您在那里看到的,如果您將使用shouldComponentUpdate阻止重新渲染當前元素,則不會使用shouldComponentUpdate渲染方法。

但是不要擔心React 只會更新什么是必要的 所以,如果你的父元素的 html 不會改變,真正的 DOM 只會更新子元素的 html。


展示案例

官方文檔中有一個關於如何創建表單的示例 簡而言之,您的主要問題是您沒有將值保存在任何地方,正如我所見,您使用 Redux 並通過 props 傳遞所有數據。 嘗試更改您的代碼,將數據保存在組件自己的狀態中。

如果您在 BadRequest 上發現錯誤,您將觸發代碼,檢查相等性,例如消息(錯誤)並更新您的組件,但您的當前狀態以及所有用戶的數據都不會更改

shouldComponentUpdate(nextProps, nextState) {
    //there you will get the new values and check it, if they not equal
}

componentDidUpdate(prevProps, prevState) {
    //there you can do anything with your new values
}

如果您使用 Redux,請查看Redux Form

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM