如何使REST API进入以在React JS中显示数据

时间:2019-05-27 08:28:08

标签: php reactjs rest api

请帮助我在php中制作简单的rest api,以从数据库中获取数据并显示为react js

我有3列名称,部门和标记。 这是我的PHP代码-

<?php 

header("Content-Type: application/json; charset=UTF-8");
$con = mysqli_connect("mysql1004.mochahost.com","a310387_task_for","task_force","a310387_task_force");

    $query=mysqli_query($con,'select * from student');
$json_array=array();
while($rows=mysqli_fetch_assoc($query)){
    $json_array[]=$rows;
 }
 echo json_encode($json_array);

 ?>

这是我的反应代码-

 componentDidMount(){
    fetch('http://veomit.com/test/zend/api/fetch.php')
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                });
    });
  }

显示类似-

 <tbody>
            <tr>
              {
                        this.state.UserData.map(function(item, key) {             
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                                </tr>
                            )
                        })
                    }
            </tr>
          </tbody>

请帮助我纠正此问题。 预先感谢。

1 个答案:

答案 0 :(得分:1)

工作code

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    userData: []
  };
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts") // could be any rest get url
      .then(response => response.json())
      .then(result =>
        this.setState({
          userData: result
        })
      );
  }
  render() {
    return (
      <div className="App">
        <table>
          <tbody>
            {this.state.userData.map((data, key) => {
              return (
                <tr key={key}>
                  <td>{data.userId}</td> // column data received
                  <td>{data.title}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

希望有帮助!