【问题标题】:Can not get the data response无法得到数据响应
【发布时间】: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() 函数中,以查看数据是否正确接收并告知我们

标签: reactjs axios


【解决方案1】:

您确定res.data.name 存在吗?

res.data 似乎返回数组。

您应该将用户状态声明为 null,并将用户状态设置为 res.data

之后,您可以使用Array.prototype.mapres.data

例如,

state = {
   users: null,
   whatever: ''
}

componentDidMount() {
    axios
    .get('https://jsonplaceholder.typicode.com/users')
    .then(res => this.setState({ 
        users: res.data
    }));
  }

...

// write function that takes id as parameter.
this.state.users.map(item => {
    if(item.id === id){
        this.setState({
            whatever: item.name
        })
    } return item;
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2015-04-01
    相关资源
    最近更新 更多