开发者问题收集

React API 数据未显示在 JSX 中

2021-04-21
453

[在此处输入链接描述][1]我正在 React 中获取 API。我能够在控制台中看到数据,但它没有出现在 JSX 中。我想查看数据 ID、名称和值。但它没有出现在浏览器中。

[1]: https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js

import React  from 'react';
import axios from 'axios'
import './App.css';

class Main extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            users: [],
            error: ''
        }
    }

    componentDidMount(){
        axios.get('https://jsonplaceholder.typicode.com/users')
        .then( response => {
            console.log(response);
            this.setState({users: response.data})
        })
        .catch(error =>{
            console.log(error);
        })
    }

  render() {
      const { users } = this.state
      return (
          <div>
              <h2> Main Page</h2>
              <p class="para-text"> Data from API</p>
              {
                  users.length ?
                  users.map(post => <div key ={ users.id }> {   users.name} </div>) : null
              }

          </div>
      );
  }
}
export default Main;
1个回答

映射时,您将地图的键命名为 post,因此在 jsx 中显示它们时,您必须引用该键

附件是您的沙盒的分叉版本 https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js

import "./styles.css";

import React from "react";
import axios from "axios";

class Main extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
      error: ""
    };
  }

  componentDidMount() {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((response) => {
        this.setState({ users: response.data });
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    const { users } = this.state;

    return (
      <div>
        <h2> Main Page</h2>
        <p class="para-text"> Data from API</p>
        {users.length > 0
          ? users.map((post) => <div key={post.id}> {post.name} </div>)
          : null}
      </div>
    );
  }
}
export default Main;
Rob Terrell
2021-04-21