【问题标题】:React Promise - TypeError: Cannot read property 'then' of undefinedReact Promise - TypeError:无法读取未定义的属性'then'
【发布时间】:2018-01-15 05:03:48
【问题描述】:

我正在从以下返回对象的调用中获取数据:

function getPersonList() {
        const api = 'myapistring';
        axios.get(api).then(res => {
            console.log(res);
        }).catch(err => console.log(err));
}

1 - 但是当我点击我的 componentDidMount 时。诺言破灭了,我不知道为什么。

2- 另外,由于响应是一个对象,我是否通过将初始状态设置为空 [] 做错了什么? -我不确定将其设置为对象的语法是什么。

const App = React.createClass({
    getInitialState() {
        return {
            personList: [],
            visiblePersonList: []
        };
    },
    componentDidMount() {
         console.log(getPersonList(response));
        getPersonList().then((data) =>
            this.setState({
                data,
                visiblePersonList: data
            }));
        //return getPersonList;
    },
.....

谢谢大家!

【问题讨论】:

  • 虽然提供空数组(如[])作为即将成为对象的初始值是相当安全的,但最好为它们分配空对象:{}。见docs。
  • @RishatMuhametshin 听起来没有意义,它们应该是后缀为 List 的数组。
  • @DanielA.White 数组 + 后缀列表的正确语法是什么?
  • 可以将它们作为空数组 IMO。

标签: javascript reactjs react-native es6-promise axios


【解决方案1】:

你没有从getPersonList返回任何东西

function getPersonList() {
    const api = 'myapistring';
    return axios.get(api).then(res => {  // FIX THIS LINE WITH return
        console.log(res);
    }).catch(err => console.log(err));
}

【讨论】:

  • 非常感谢丹尼尔!
猜你喜欢
  • 2014-11-26
  • 2018-06-02
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多