javascript - 将 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 object
的getKeys
功能。
我假设,这是因为返回的承诺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 的新手,通常在后端工作,所以如果我缺少某种基本概念,指出这一点会很有帮助。
解决方案
您可能应该添加一些状态处理来异步获取内容。例子:
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} />;
推荐阅读
- c - 为什么我的代码在提示用户后没有返回所需的输出
- linux - 如何将 find 返回的文件列表通过管道传输到 cat 并对它们进行排序
- jquery - jQuery,如何用千位分隔符替换滑块的值?
- java - java中的快速排序程序
- ssl - Tomcat 8.5 多个域使用多个证书存储
- python - Numpy 创建一个空的 alpha 图像
- javascript - 根据日期+持续时间(分钟)对数组(甘特计划)进行排序 - 带有静态中断(日期+持续时间)
- xpath - XQuery - 地图合并问题 - 执行 xbase
- android - 关闭所有意图并关闭应用程序
- python - 如何保存神经网络模型的所有细节?