简体   繁体   中英

React JS 'this' not working as expected

I have the below code

save: function() {
        var _this = this;

        console.log(this.refs.itemText)

        this.setState({isEditing : false}, 
            function() {
                console.log("Inside call back");
                console.log(_this.refs);
                console.log(_this.refs.itemText);
             }   
        );    
    },

but _this is not accessible inside the callback function. Is this a scope issue?

See demo here

The correct place to work with refs is inside specific React lifecycle methods eg 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 .

I checked your code, everything is working fine. the problem is with your logic.

let me explain you whats going wrong.

  1. when you are in edit mode, your itemText is rendered so its available in refs so it shows correct console log.

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM