【问题标题】:How to make rest api in to to display data in react js如何使rest api在react js中显示数据
【发布时间】:2019-10-12 19:24:25
【问题描述】:

请帮我在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>

请帮我纠正这个问题。 提前致谢。

【问题讨论】:

    标签: php reactjs rest api


    【解决方案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);
    

    希望对你有帮助!!!

    【讨论】:

    • 我的反应代码工作正常,但我认为我的休息 api 是错误的......所以请帮我纠正我的 api
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2020-04-30
    • 2021-04-27
    相关资源
    最近更新 更多