简体   繁体   中英

setState in reactjs inside success function not setting state

I am using a ParsePlatform as backend storage and reactjs as front end. I am able to get the parse data using Parse.Query but unable to use the returned values as I do not know how to set the state from the successfull fetching of results. I tried like this way inside componentDidMount()

import React from 'react'
import Parse from 'parse'
class ConferenceInfo extends React.Component {
    state={
        someData:null
    }
    componentDidMount(){
        this.getConferenceInfo()
    }
    getConferenceInfo(){
        var ConferenceListing = Parse.Object.extend("ConferenceListing");
        var cl = new Parse.Query(ConferenceListing);

        cl.get("8glBIjeRrC", {
            success: function(cl) {
                // The object was retrieved successfully.
                alert(cl.get("someData")) //it works
                //this.setState({someData:cl.get("someData")}) not working              
            },
            error: function(object, error) {
                // The object was not retrieved successfully.
                // error is a Parse.Error with an error code and message.
            }
        });
    }
    render() {
        return (
            <div>
                {this.state.someData} //no result
            </div>
        )
    }
}
export default ConferenceInfo

This is because this is not in the same scope. You are calling it inside success property, function callback.

To get it working we need to bind this .

First Create constructor method.

constructor(props) {
  super(props);
  // Our new bind method ref
  this.change = this.change.bind(this);
}

Then add new method change

change(obj) {
  this.setState(obj);
}

Finally your success callback

success: function(cl) {
  // ...
  this.change({ someData: cl.get("someData") })           
},

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