简体   繁体   中英

I am having an error while updating my states in react

While trying to update the state from a function and calling the function from componentdidmount lifecycle method, the state doesn't update. But when I try to update the state by calling the function from inside the jsx, it does work. I dont know what is happening

//my state
constructor(){
    super()
    this.state = {
        activepage:'dashboard',
        language:[],
    }
}

//the function I am updating state from
getLanguage = () => {
    axios.get('http://localhost:3001/language')
        .then(function (response) {
            console.log(response.data.language);
            this.setState({
                language:response.data.language
            })
        })
        .catch(function (error) {
            return error;
    });
}

//I am calling function from
componentDidMount(){
    this.getLanguage();
    console.log("state after updating",this.state) //displays an empty array
}

But when I call function getLanguage from inside the jsx it updates the state.

update your function with es6 arrow function

.then((response) => {
        console.log(response.data.language);
        this.setState({
            language:response.data.language
        })
    })

For es6 you can use arrow function

getLanguage = () => {
    axios.get('http://localhost:3001/language')
        .then((response) => {
            console.log(response.data.language);
            this.setState({
                language:response.data.language
            })
        })
        .catch((error) => {
            return error;
        })
    );
}

For es5 you can declare this out of scope axios function

function getLanguage() {
    var self = this;
    axios.get('http://localhost:3001/language')
        .then(function(response) {
            console.log(response.data.language);
            self.setState({
                language:response.data.language
            })
        })
        .catch(function(error) {
            return error;
        })
    );
}

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