【问题标题】:ItemList.js:15 Uncaught TypeError: items.map is not a functionItemList.js:15 Uncaught TypeError: items.map 不是函数
【发布时间】:2023-02-15 19:32:50
【问题描述】:

我使用 React Js 作为前端,使用核心 Php 作为后端。我通过 Mysql 中的表单存储数据,然后想在另一个页面的 UI 中显示该数据。没有使用道具。下面是我的 React js 代码

import React, { useState, useEffect } from "react";
import { Container, Row, Col } from "react-bootstrap";
import axios from "axios";

function ItemList() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    axios.get("http://localhost/reactphp/items/").then(function (response) {
      setItems(response.data);
      // console.log(items);
    });
  }, []);
  return (
    <Container>
      <Row>
     
        {items.map((item, key) => (
          <Col lg="4" sm="6" key={key}>
            <img src={item.image} alt="pic" />
            <h3>{item.name}</h3>
            <span>{item.price}</span>
          </Col>
        ))}
      </Row>
    </Container>
  );
}

export default ItemList;

下面是我的 Php 代码。

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Origin: *");
include 'conn.php';
$getData = "SELECT * FROM items";
$result = $conn->query($getData);
$data = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}
echo json_encode($data);
print_r($data);
?>

我几乎到处都试过了,但得不到答案

【问题讨论】:

  • 在 php header('Content-Type: applicatiton/json'); 中添加这个

标签: php reactjs


【解决方案1】:

我认为 print_r($data); 弄乱了回报。只需将其删除。

<?php
    $myArray = ["foo", "bar"];
    echo json_encode($myArray);
    print_r($myArray);
    
    /**
     * Output an invalid JSON
     * 
        ["foo","bar"]Array
        (
            [0] => foo
            [1] => bar
        )
     *
     */

【讨论】:

    猜你喜欢
    • 2022-10-22
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2019-11-06
    • 2017-09-18
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多