React JS 'this' Not Working As Expected
Solution 1:
I checked your code, everything is working fine. the problem is with your logic.
let me explain you whats going wrong.
when you are in edit mode, your itemText is rendered so its available in refs so it shows correct console log.
when you save and change the state, it re-renders the form and since your state got changed, your input element is now hidden. hence it returns undefined when you try to access its refs.
i hope this will answer your questions.
Solution 2:
The correct place to work with refs is inside specific React lifecycle methods e.g. ComponentDidMount, ComponentDidUpdate.
In your case, if you want to do something right after the state is changed, hook-up on the componentDidUpdate
method (instead of using the this.setState
callback).
Read more about the cautions of working with refs here.
Post a Comment for "React JS 'this' Not Working As Expected"