当我更新超级组件的状态时,其中内部被路由器包裹的组件也会重新渲染,这会将子组件的状态重新启动为其默认值。即使我没有将任何道具传递给sub且没有任何依赖性。
我应该如何防止这种情况?您可以找到它的演示here。 (只需切换sub的状态,然后更改super的状态,您就会看到发生了什么)。
您的问题有一个简单的解决方法!
在index.js
中,更改此行:
<Route exact path="/" component={props => <Sub {...props} />} />
使用此:
<Route exact path="/" render={props => <Sub {...props} />} />
component
和render
之间具有匿名功能的区别在于,component={() => <YourComponent />}
将始终在父级显示时重新渲染。但是,对于render
,仅在必要时才进行重新渲染。
如果您想进一步了解以下主题,我建议您阅读这篇文章:https://tylermcginnis.com/react-router-pass-props-to-components/。
我在这里分叉了您的CodeSandbox示例,以查看区别:https://codesandbox.io/s/goofy-fermat-m01ct
shouldComponentUpdate在每次渲染之前触发。您可以使用它来防止重新提交。
https://busypeoples.github.io/post/react-component-lifecycle/
或者可能是您需要componentWillMount