[英]this.props.history.push is working just after refresh
我有一个反应大日历,当我点击它时有一个按钮,他的模态会出现,我还有一个日历图标按钮,它将我重定向到另一个URL /计划。
我有一个对话框(AjouterDisponibilite),我用我的组件议程中的ref调用它。
日历图标有一个onClick
事件,我尝试:
this.props.history.push('/planning');
但当我运行它并点击图标时,URL指向正确,但我收到error
,如下所示:
TypeError: Cannot read property 'handleAjouter' of null
并且Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
刷新此页面后,它可以正常工作。
我的代码是: https : //codesandbox.io/s/xw01v53oz
我该如何解决?
问题是Refs的使用不当。 Refs旨在保留对DOM元素和组件实例的引用,而不是它们的功能。
具有ref
prop的组件将在装入时将自己分配给prop的值(或者将其自身作为参数调用该函数),并且在卸载它们时它们将使用null
引用执行相同操作。
有了这些知识,您必须更改Agenda
组件的代码,如下所示:
ModalAjout = (ref) => {
if (ref) {
this.ajout = ref.handleAjouter;
} else {
this.ajout = null;
}
}
ModalAjoutb = (ref) => {
if (ref) {
this.ajoutb = ref.handleAjouter;
} else {
this.ajoutb = null;
}
}
解决此问题的最佳方法是添加以下代码:
history.pushState(null, document.title, location.href);
在做什么? 它是在第一次加载后用一个值初始化历史记录,然后您不需要进行刷新。
在我的情况下,我在开发Android应用程序时做了这个,并且我想用后退按钮关闭一些模态以提供更原生的体验。
我修正了它,添加:
<AjouterDisponibilite ref={(evt) => this.ModalAjout({evt})} start={this.state.startDisponibilite} end={this.state.endDisponibilite} date={this.state.dateDisponibilite}/>
<AjouterDisponibilite ref={(evt) => this.ModalAjoutb({evt})} />
ModalAjout
方法必须有一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.