首页 > 解决方案 > 将 JSON 数据加载到 React 表中

问题描述

我正在尝试使用我制作的 REST API 并将返回的数据转储到使用 React 的简单表中。

我知道我可以使用此行访问我的 API 并获取 JSON 数据:

 fetch('http://localhost:5000/api/v0.1/Organisations').then(r=>r.json());

如果我添加一个,.then(d=>console.log(d));我会在日志中显示数据,所以我知道我的 API 正在成功返回数据:

数据

但是,当我启动应用程序时,我正在使用我的组件Cannot convert undefined or null to objectgetKeys功能。

我假设,这是因为返回的承诺fetch尚未实现,但我不知道如何等待它。

我的组件定义:

export default class Table extends React.Component
{

    constructor(props){
        super(props);
        this.getHeader = this.getHeader.bind(this);
        this.getRowsData = this.getRowsData.bind(this);
        this.getKeys = this.getKeys.bind(this);
    }

    getKeys = function(){
        return Object.keys(this.props.data[0]);
    }

    getHeader = function(){
        var keys = this.getKeys();
        return keys.map((k,i)=>{
            return <th key={k}>{k}</th>
        })
    }

    getRowsData = function(){
        var items = this.props.data;
        var keys = this.getKeys();
        return items.map((r,i)=>{
            return <tr key={i}><RenderRow key={i} data = {r} keys={{keys}}/></tr>
        })
    }

    render() {
        return (
            <div>
                <table>
                    <thead>
                    <tr>{this.getHeader()}</tr>
                    </thead>
                    <tbody>
                    {this.getRowsData()}
                    </tbody>
                </table>
            </div>

        );
    }
}
const RenderRow = (props) =>{
    return props.keys.map((k,i) => {
        return <td key={props.data[k]}>{props.data[k]}</td>
    })
}

还有我的 app.js:

import './App.css';
import './components.js'
import React from 'react';
import Table from "./components";




function App() {
    var data = fetch('http://localhost:5000/api/v0.1/Organisations').then(r=>r.json());
    fetch('http://localhost:5000/api/v0.1/Organisations').then(r=>r.json()).then(d=>console.log(d));
  return (
    <div className="App">
      <header className="App-header">
        <h1>Vaultex Tech Test</h1>
        <h2>Organisations</h2>
        <Table data={data}/>

      </header>
    </div>
  );
}

export default App;

我是 React 的新手,通常在后端工作,所以如果我缺少某种基本概念,指出这一点会很有帮助。

标签: javascriptreactjsrest

解决方案


您可能应该添加一些状态处理来异步获取内容。例子:

import {useState, useEffect} from 'react';

//Adding a state placeholder for your result
const [myData, setMyData] = useState();
//Adding a loading state
const [loading, setLoading] = useState(true);

//Add an async load function that resolves your endpoint
const load = async () => {
  setLoading(true);
  const data = await fetch('http://localhost:5000/api/v0.1/Organisations');

  setMyData(data.json());
  setLoading(false);
}

useEffect(() => {
  //this will trigger your load function once when the component is mounted
  load();
}, []);

if (loading) return <div>Loading...</div>;

return <Table data={myData} />;

推荐阅读