Javascript 在React组件构造函数中处理承诺链
我正在从API获取数据,需要根据接收到的数据构建一个列表。问题是,呈现发生在构造函数中的获取完成之前,因此发送到Javascript 在React组件构造函数中处理承诺链,javascript,reactjs,promise,Javascript,Reactjs,Promise,我正在从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 Com
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'));
import React,{Component}来自'React';
从'react dom'导入{render};
从“./Header.jsx”导入标头
从“./List.jsx”导入列表
类应用程序扩展组件{
建造师(道具){
超级(道具)
this.todos=[]
常量url=”http://localhost:3000/api/todos/"
获取(url)
.then(res=>res.json())
。然后((数据)=>{
this.todos=数据;
})
.catch(控制台错误);
}
渲染(){
返回(
)
}
}
render(,document.getElementById('app'));
您通常希望向用户发出数据正在加载的信号。您还需要确保区分空数据和未接收的数据
您还希望此数据是组件状态的一部分,而不是类实例本身,以便在收到数据时允许组件重新呈现
=>this.state.todos
而不是this.todos
类示例扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
待办事项:空
}
设置超时(()=>{
这是我的国家({
待办事项:[1,2,3]
})
}, 1000);
}
渲染(){
返回(
{this.state.todos
?{this.state.todos.toString()}
:正在加载待办事项。。。
}
)
}
}
ReactDOM.render(,document.getElementById('app'))代码>
将异步操作放在构造函数中通常被认为是不好的做法。这是因为没有一种干净的方式来回传一个承诺,调用者可以从中确定异步操作何时完成或是否有错误。有关三个单独的设计解决方案,请参见。我最喜欢的方法是使用一个工厂函数来创建对象,然后调用该对象上的一个方法来执行异步操作,并返回一个承诺谁的解析值是新对象。react文档说永远不要在构造函数中使用setState您能不能进一步完善答案?