【问题标题】:I am having an error while updating my states in react我在更新我的反应状态时出错
【发布时间】:2018-12-28 11:22:33
【问题描述】:

在尝试从函数更新状态并从 componentdidmount 生命周期方法调用函数时,状态不会更新。 但是当我尝试通过从 jsx 内部调用函数来更新状态时,它确实有效。我不知道发生了什么

//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
}

但是当我从 jsx 内部调用函数 getLanguage 时,它会更新状态。

【问题讨论】:

  • 当您更新state 时,它不会立即更新。您可以使用setState 回调来查看状态何时更新。看到这个:stackoverflow.com/a/50604716/4089357
  • 你用反应开发工具检查,而不是控制台,这里也是
  • 谢谢你。它成功了

标签: node.js reactjs api axios


【解决方案1】:

用 es6 箭头函数更新你的函数

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

【讨论】:

  • @MUsmanNadeem 这没有任何意义,如果这是问题所在,在这两种情况下都不应该更新(但他说它确实通过 jsx 更新)。
  • 成功了。我添加了一个回调,它工作正常
【解决方案2】:

对于es6,您可以使用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;
        })
    );
}

对于es5,您可以声明this 超出范围axios 函数

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;
        })
    );
}

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 2022-07-18
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多