dongpixi2648 2019-05-15 10:10
浏览 80

如何使用带有reactjs的php rest api?

I want to create a frontend using react for my PHP rest API. I try to read the data from the rest api but I can't manage to fetch it properly. I tested all the requests in Postman and they work fine, but I have no clue why they don't work in react.

I tried to do it with axios/fetch/get but I always get the same error TypeError: items.map is not a function. Should I rewrite my rest API? My API is returning a JSON and I don't know if I need to decode it in react?

My php code:

public function read() {
    // Create query
    $query = 'SELECT * FROM ' . $this->table ;

    // Prepare statement
    $stmt = $this->conn->prepare($query);

    // Execute query
    $stmt->execute();

    return $stmt;
}

API readUM.php

<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Post2.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate  post object
$post = new Post2($db);
// Blog post query
$result = $post->read();
// Get row count
$num = $result->rowCount();
// Check if any posts
if ($num > 0) {
// Post array
$posts_arr = array();
 $posts_arr['data'] = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $post_item = array(
        'id' => $id,
        'name' => $name,
        'location' => $location,
        'type' => $type,
        'logo' => $logo
    );
    // Push to "data"
    //array_push($posts_arr, $post_item);
    array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
    array('message' => 'No Posts Found')
);
}

Result in postman:

{
"data": [
    {
        "id": "1",
        "name": "Test",
        "location": "Cluj",
        "type": "Test",
        "logo": null
    }
]
}

My react code:

 constructor(props) {
    super(props);
    this.state = {
        items: [],
        isLoaded: false,
    }
}

componentDidMount() {

    fetch('http://localhost/fak/api/post/readUM.php')
        .then(res => res.json())
        .then(json => {
            this.setState({
                isLoaded: true,
                items: json,
            })
        });
}

render() {

    let {isLoaded, items} = this.state;

    if (!isLoaded) {
        return <div>Loading...</div>
    } else {
        return (
            <div className="App ">
                <ul>
                    {items.map(item => (
                        <li key={item.id}>
                            Name:  {item.name} | Location:{item.location} 
                        </li>
                    ))};
                </ul>
            </div>
        );
    }
    }
}

Console.log(json):

Object
data: Array(1)
0: {id: "1", name: "Test", location: "Cluj", type: "Test", logo: null}
length: 1
__proto__: Array(0)
__proto__: Object
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 buildozer打包kivy app失败
    • ¥30 在vs2022里运行python代码
    • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
    • ¥15 求解 yolo算法问题
    • ¥15 虚拟机打包apk出现错误
    • ¥15 用visual studi code完成html页面
    • ¥15 聚类分析或者python进行数据分析
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复