首页 > 解决方案 > 为什么来自 API 的 Json 没有在表格上呈现

问题描述

所以今晚我想玩 ReactTable 从 API 获取信息并显示在桌面上。这是 PHP 制作的 REST API https://librational-`talker.000webhostapp.com/peopleBase/employee_informationAPI.php 所以现在我希望它从 componentDidmount() 加载数据,它应该填充表并显示所有数据桌子

我有这个作为一个空表

2552.png

当我运行 API 时,我得到了这个

果酱3.png

我想知道为什么它没有显示在表格中。

我的代码看起来像这样

import React , { Component } from 'react';
import axios from 'axios'
import ReactTable from "react-table"; 
import 'react-table/react-table.css'

export default class HomePage extends Component {

    constructor(props){
        super(props)
        this.state = {
          users: [],
          loading:true
        }
      }

      async getUsersData(){
        const res = await axios.get('https://librational-talker.000webhostapp.com/peopleBase/employee_informationAPI.php')
        console.log(res.data)
        this.setState({loading:false, users: res.data})
      }
      componentDidMount(){
        this.getUsersData()
      }

    render() {

        const columns = [{  
            Header: 'ID',  
            accessor: 'ID',
           }
           ,{  
            Header: 'Firstname',  
            accessor: 'Firstname' ,
            }
           
           ,{  
           Header: 'Lastname',  
           accessor: 'Lastname' ,
           }
           ,{  
           Header: 'Gender',  
           accessor: 'Gender',
           },
           {  
            Header: 'DOB',  
            accessor: 'Date_of_birth',
            },
            {  
              Header: 'Email',  
              accessor: 'Email',
              },
              {  
            Header: 'Telephone',  
             accessor: 'Telephone',
            },
            {
                Header: 'NationalIDNumber',  
                accessor: 'NationalIDNumber',
            },
            {
                Header: 'PassportNumber',  
                accessor: 'PassportNumber',
            },
            {
                Header: 'Salary',  
                accessor: 'Salary',
            },
        ]

        return (
            <ReactTable  
            data={this.state.users}  
            columns={columns}  
         />
           );
    }

}

有什么我似乎在这里遗漏或做得不正确吗?请我需要帮助。对此非常陌生。

编辑

交叉检查,我看到了这个

805405.png

所以我从 Webhosting 启用了 CORS。但它仍然没有提取数据并在表格上显示信息。

我该怎么做?

标签: reactjsaxiosreact-table

解决方案


我相信这是因为您的端点“https://librational-talker.000webhostapp.com/peopleBase/employee_informationAPI.php”您正试图将 PHP 文件作为对象读取。本质上这是 PHP 的结果。

您需要为您的 API 路径创建一个常量并处理数据以正确格式化。像这样的东西。

const API_PATH = https://librational-talker.000webhostapp.com/peopleBase/employee_informationAPI.php


 getUsersData = e => {
  e.preventDefault();
  axios({
    method: 'users',
    url: `${API_PATH}`,
    headers: { 'content-type': 'application/json' },
    data: this.state
  })
    .then(result => {
       this.setState({ loading: false, users: res.data });
    })
    .catch(error => this.setState({ error: error.message }));
};

可能需要一些调整,但希望这能让你朝着正确的方向前进?


推荐阅读