我在 React 调用中完成了一个函数,该函数调用 api,并根据该 api 接收到的数据设置状态
getUserList() {
API.get('/userlist')
.then(response => {
this.setState({
userList: response.data
}, () => {
console.log(this.state.userList) //I can see this
});
})
}
这就是我的构造函数的样子
constructor(props) {
super(props)
this.state = {
retracted: false,
userList: []
}
this.getUserList = this.getUserList.bind(this);
}
我在 componentDidMount() 中调用它
componentDidMount() {
this.getUserList();
}
但是我的渲染崩溃了,因为两个 console.log 都返回未定义
kết xuất() {
var users = this.state.userList;
var user = users[0].email //cannot read email of undefined
console.log(this.state.userList)
console.log(users)
trở lại (
)
}
componentDidMount
KHÔNG异步
,也不可能是。您应该在异步调用期间处理诸如loading
之类的转换状态。
考虑进行检查,因为尚未获取结果:
kết xuất() {
var users = this.state.userList;
if (users.length === 0) {
return loading
}
return {users[0].email}
}
根据您的使用情况,这可能不完全有效,特别是对于错误响应。您仍然会检查 error
情况/状态,其中 users.length === 0
但不检查loading
.
Tôi là một lập trình viên xuất sắc, rất giỏi!