【发布时间】:2019-11-11 11:42:10
【问题描述】:
我正在尝试从虚假的在线休息 api 获取一些数据到我的状态,问题是数据没有正确地进入状态,所以它没有显示出来。
我尝试将状态更改为数组或像这样firstName: '',
...,但它仍然无法正常工作
import React, { Component } from 'react';
import axios from 'axios';
class Success extends Component {
state = {
firstName: [],
username: [],
email: [],
id: [],
show: false
};
componentDidMount() {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then(res => this.setState({ firstName: res.data.name }));
}
onClick = () => {
this.setState(prevState => ({ show: !prevState.show }));
};
render() {
return (
<div>
<h1
className="font-weight-light"
style={{
color: 'black',
marginTop: '50px'
}}
>
UserList:
</h1>
<div className="mt-5">
<ul className="list-group">
<li className="list-group-item">
{this.state.firstName}
<div
className="fas fa-angle-down"
style={{ marginLeft: '98%' }}
onClick={this.onClick}
/>
</li>
{this.state.show === true ? (
<li className="list-group-item">
Username: {this.state.username}
</li>
) : null}
{this.state.show === true ? (
<li className="list-group-item">Email: {this.state.email}</li>
) : null}
{this.state.show === true ? (
<li className="list-group-item">ID: {this.state.id}</li>
) : null}
</ul>
</div>
</div>
);
}
}
export default Success;
我想在状态中获取该数据并显示出来。
【问题讨论】:
-
尝试将 console.log 添加到您的 axios .then() 函数中,以查看数据是否正确接收并告知我们