Reputation: 1932
I have a react-big-calendar, which has a button when I click on it, his modal will appear, and I have also a calendar icon button which redirects me to another URL /planning.
I have a dialog (AjouterDisponibilite) and I call it with the ref on my component Agenda.
And the calendar icon has an onClick
event which I try:
this.props.history.push('/planning');
but when I run it and I click on the icon, the URL is directed correct, but I get an error
as shown below:
TypeError: Cannot read property 'handleAjouter' of null
and
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
and after I refresh this page, it works.
My code is: https://codesandbox.io/s/xw01v53oz
How can I fix it?
Upvotes: 3
Views: 2979
Reputation:
The problem is improper use of Refs. Refs are designed to keep references to DOM-elements and component instances, not their functions.
Components with a ref
prop will assign themself to the value of the prop (or call the function with itself as an argument) when they are mounted, and they will do the same with a null
reference when they are unmounted.
With this knowledge, you have to change your code of the Agenda
component as follows:
ModalAjout = (ref) => {
if (ref) {
this.ajout = ref.handleAjouter;
} else {
this.ajout = null;
}
}
ModalAjoutb = (ref) => {
if (ref) {
this.ajoutb = ref.handleAjouter;
} else {
this.ajoutb = null;
}
}
Upvotes: 3
Reputation: 1932
I fix it, by adding:
<AjouterDisponibilite ref={(evt) => this.ModalAjout({evt})} start={this.state.startDisponibilite} end={this.state.endDisponibilite} date={this.state.dateDisponibilite}/>
<AjouterDisponibilite ref={(evt) => this.ModalAjoutb({evt})} />
The method ModalAjout
must have a parameter.
Upvotes: 2
Reputation: 3274
The best way to solve this you can add this code:
history.pushState(null, document.title, location.href);
What is doing? It's initializing the history with one value after it was loaded the first time, then you don't need to do the refresh.
In my case I did this while I was developing an Android App and had some modals that I wanted to close with the back button to provide a more native experience.
Upvotes: 2