首页 文章

React promise返回undefined

提问于
浏览
2

我有一个返回数组的函数

myfunc: func(){
    myArr = ['hello']
    //does other things

    return myArr;
}

在顶部我称之为此功能

this.myfunc();
    }).then((myArr) => {
      this.setState({myArr: myArr});
      console.log(myArr);
    });

为什么myArr被记录为未定义?当然应该在promise中的状态中设置返回数组的内容?

与往常一样,我尝试发布最少的代码,但可以添加更多 . 我正在尝试使用promises和setState并在响应中更改该状态 . 由于某种原因,此时尚未定义

1 回答

  • 1

    你的功能没有回复承诺 . 我认为这会奏效:

    let p = new Promise(function(resolve, reject)) {
        resolve(['hello']);
    }
    
    p.then(function(value) {
        setState({key: value});
        console.log(value);
    });
    

相关问题