[英]cannot display fetched api data in ReactJS
我正在尝试从获取的 api 数据中显示用户的名字......这个 Reactjs 代码可能有什么问题? 我确认已经从 api 中获取了数据,但是在显示它时......它返回空白并且没有错误
class App extends Component
constructor() {
super()
this.state = {
loading: false,
user: {}
}
}
componentDidMount() {
this.setState({loading: true})
fetch("https://reqres.in/api/users/2")
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
user: data
})
})
}
render() {
const text = this.state.loading ? "loading..." : this.state.user.first_name
return (
<div>first name: {text}</div>
)
}
}
export default App
您在最后的then
回调函数中命名整个响应data
。 响应本身还包含另一个名为data
对象,以访问您应该在setState
使用data.data
对象。
您可能希望在回调中像这样解构它:
fetch("https://reqres.in/api/users/2")
.then(response => response.json())
.then({data} => {
this.setState({
loading: false,
user: data
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.