【问题标题】:Unable to display API data on React.js无法在 React.js 上显示 API 数据
【发布时间】:2018-06-04 21:43:16
【问题描述】:

我正在尝试在 React.js 前端显示来自本地 API 的数据。

它显示了一个只有表格标题的空白表格,但表格上没有条目。 JSON 来自 API,就好像我 console.log(this.state.cards) 它在命令行上记录数组一样。

感谢任何帮助!

谢谢!

import React, { Component } from 'react';
import '../css/card.css';
import Card from './Card';
import CardTable from './CardTable.js';
import request from 'request';

class TopCards extends Component {

    constructor() {
        super();
        this.state = {
          cards: [],
        };
      }

    componentDidMount() {
        const url = "http://localhost:1200";
        request({
            url: url,
            json: true
        }, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                for (let i in body) {
                    this.state.cards.push(body[i]);
                }
            }
        })
    }

    render() {


        if(this.state.cards) {
            var cardList = this.state.cards.map(function(card){
                return(
                    <CardTable key={card.cardName} card={card} />
                );
            });
        }

        return (
            <div className="TopCards">
                <h1>Top Cards This Week:</h1>
                <br />
                <table width="400">
                <tr>
                        <th>Name</th>
                        <th>Count</th>
                        <th>Wins</th>
                        <th>Losses</th>
                        <th>Win %</th>
                </tr>
                    {cardList}
                </table>
            </div>
        )
    }
}

export default TopCards;

【问题讨论】:

    标签: sql reactjs api fetch


    【解决方案1】:

    你需要setState 通知 React 你想要渲染一些东西。其次,您应该确保使用不可变的数据结构。 pushunshift 不要通知任何更改。

    for (let i in body) {
        this.setState({
            cards: [
                ...this.state.cards,
                body[i]
            ]
        });
    }
    

    【讨论】:

    • 感谢您的回复!正如您所做的那样,我已将 for (let i in body) 更改为 setState。表中仍然没有数据。此外,console.log 不再通过 JSON 数组。还有其他建议吗?
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多