[英]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.