【问题标题】:How prevent rerender of parent component in React.js如何防止在 React.js 中重新渲染父组件
【发布时间】:2017-02-06 12:52:23
【问题描述】:

我有一个组件 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>
    );

当我在子组件中编辑某些信息时,我的父组件会重新渲染,但我想阻止它。我该怎么办?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这是不可能的,因为只有在重新渲染父组件时才会调用重新渲染子组件。

    如您所见there,如果您将使用shouldComponentUpdate 阻止重新渲染当前元素,则不会使用子渲染方法。

    但不要担心React Only Updates What's Necessary。所以,如果你的父元素的 html 不会改变,那么真正的 DOM 将只更新子元素的 html。


    展示案例

    官方文档中有一个example,说明如何创建表单。简而言之,您的主要问题是您没有将值保存在任何地方,正如我所见,您使用 Redux 并通过道具传递所有数据。尝试更改您的代码,以将数据保存在组件自己的状态中。

    如果您在 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

    【讨论】:

    • 我的子组件中有表单,如果我发送错误响应的 api 调用,我的表单会重新呈现,所有数据都消失了。也许你遇到同样的问题,可以帮助我
    • 已更新以包含一些描述
    猜你喜欢
    • 2019-12-01
    • 2020-03-18
    • 2021-02-06
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多