【问题标题】:How to render fetched data from API如何渲染从 API 获取的数据
【发布时间】:2019-01-12 16:38:31
【问题描述】:

我正在尝试从要在表格中呈现的 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;

【问题讨论】:

  • this.setState({users: users}) 是异步的。这意味着当您尝试访问 this.state 时,您无法确定它是最新版本的 state。

标签: javascript reactjs api fetch


【解决方案1】:

好的,所以经过一些修补后,我能够解决它。

我从:

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}/>
});

【讨论】:

  • 看起来问题出在你有data.response.map 的地方,而你需要data.map,因为你的响应是如何配置的。我敢打赌,它仍然可以通过仅更改那一部分来与原始示例一起使用,但我猜你想使用你的 Row 组件并且你只明确地编写了 位来调试问题......
  • 正确! @JSONaLeo
猜你喜欢
相关资源
最近更新 更多
热门标签