如何呈现从API获取的数据

时间:2019-01-12 16:38:32

标签: javascript reactjs api fetch

我正在尝试从要在表中呈现的API提取数据。我正在关注此示例,并且还尝试了其他示例: https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2

当我尝试console.log时,我得到的状态是不确定的。当我console.log数据时,我会收到正确的数据。我知道如何使用纯JavaScript解决问题,但我确实想以这种方式工作。

import React from "react";
import Row from '../components/Row';

class Table extends React.Component {

constructor() {
    super();
    this.state = {
        users: [],
    };
    this.createNewUser = this.createNewUser.bind(this);
    this.deleteExistingUser = this.deleteExistingUser.bind(this);
}

componentDidMount() {
    console.log("Component did mount!");
    fetch("http://localhost:8080/users")
        .then(response => {
            return response.json();
        }).then(data => {
        let users = data.response.map((row) => {
            return (
                <tr>
                    <td>{row.name}</td>
                    <td>{row.email}</td>
                    <td>{row.phone}</td>
                    <td>{row.age}</td>
                    <td>
                        <button className="red waves-effect waves-light btn">
                            Delete
                        </button>
                    </td>
                </tr>
            );
        });
        this.setState({users: users});
        console.log("state", this.state.users);
    });
}

render() {
    return (
        <table id="" className="highlight centered">
            <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Age</th>
                <th>Delete</th>
            </tr>
            </thead>
            <tbody id="table_body">
            {this.state.users}
            </tbody>
        </table>
    );
}
}

export default Table;

1 个答案:

答案 0 :(得分:0)

Okey,所以经过一番修补,我能够解决它。

我从:

let users = data.response.map((row) => {
        return (
            <tr>
                <td>{row.name}</td>
                <td>{row.email}</td>
                <td>{row.phone}</td>
                <td>{row.age}</td>
                <td>
                    <button className="red waves-effect waves-light btn">
                        Delete
                    </button>
                </td>
            </tr>
        );
    });

收件人:

let users = data.map((row) => {
    return <Row key={row.email} name={row.name} email={row.email}
            phone={row.phone} age={row.age}/>
});