【发布时间】:2018-12-06 08:41:17
【问题描述】:
我正在从我的 API 中获取数据,并且需要根据收到的数据构建一个列表。问题是,渲染发生在构造函数中的获取完成之前,因此发送到List 组件的this.todo 恰好是空的。处理这个问题的正确方法是什么?
import React, { Component } from 'react';
import {render} from 'react-dom';
import Header from './header.jsx'
import List from './list.jsx'
class App extends Component {
constructor(props) {
super(props)
this.todos = []
const url = "http://localhost:3000/api/todos/"
fetch(url)
.then(res => res.json())
.then((data) => {
this.todos = data;
})
.catch(console.error);
}
render () {
return (
<div>
<Header />
<List tasks={this.todos}/>
</div>
)
}
}
render(<App/>, document.getElementById('app'));
【问题讨论】:
-
将异步操作放在构造函数中通常被认为是不好的做法。这是因为没有一种干净的方式来回传一个 Promise,调用者可以从中确定异步操作何时完成或是否有错误。请参阅Node constructor not blocking 了解三种独立的设计解决方案。我最喜欢的是使用一个工厂函数来创建对象,然后在其上调用一个方法来执行异步操作并返回一个 promise,其解析值是新对象。
标签: javascript reactjs promise