为什么不在React ES6类构造函数中进行AJAX调用?

时间:2016-04-01 23:03:14

标签: javascript ajax reactjs

React docs说我应该进行AJAX调用以在componentDidMount()中设置状态,而不是构造函数。根据我看到的所有示例,这就是我应该如何从服务器加载数据:

constructor() {
    super();
    this.state = {toDoItems: []};
}

componentDidMount() {
    loadToDoItems()
        .then(items => this.setState({toDoItems: items}));
}

为什么不在构造函数中加载服务器数据,如下所示?:

constructor() {
    super();
    loadToDoItems()
        .then(items => this.state = {toDoItems: items});
}

0 个答案:

没有答案