繁体   English   中英

从数据库中获取数据并设置为React.js组件状态

[英]fetch() data from database and set as React.js component state

试图上帝的爱从我的数据库中获取数据并放入我的React Component状态,但无法理解我在做什么错。 这是我的PHP文件:

<?php

  $servername = "localhost";
  $username = "root";
  $password = "root";
  $dbname = "maggan";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

  // Check connection
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $sql = "SELECT * FROM Items";
  $result = $conn->query($sql);
  while($row = mysqli_fetch_assoc($result))
  $items[] = $row;
  echo json_encode($items);

  $conn->close();

?>

这是我的React组件:

import React, { Component } from 'react';

// Component import
import Menu from './components/menu';
import Footer from './components/footer';
import ProductContainer from './components/productContainer';
import CategoryContainer from './components/categoryContainer';

class Archive extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      products: [],
      category: ""
    }
    this.filterHandler = this.filterHandler.bind(this);
  }

  // Set component state to the currently clicked "cat" (CategoryItem)
  filterHandler(tag){
    this.setState({
      category: tag
    })
  }

  componentDidMount(){
    fetch("/getProducts", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    })
    .then(async res => {
      const data = await res.json();
      setState({
        products: data
      })
    })
    .catch(function(err) {
      console.log('ERROR!!! ' + err.message);
    });
  }

  render() {
    // 1. Render CategoryContainer with props products and filterHandler function to show all uniqe CategoryItems and filter products based on category
    // 2. Render ProductContainer based on category. If this.state.category.length is true - filter "prod" & where prod.categories is same type and name as this.state.category : else render all this.state.categories that matches "paint".
    return (
      <div>
        <Menu />
        <div className="archive-container">
          <div className="archive-wrapper">
            <CategoryContainer
              filterHandler={this.filterHandler}
              products={this.state.products}
            />
            <br/><br/>
            <ProductContainer
              products={this.state.category.length
                ? this.state.products.filter((prod) => prod.category === this.state.category)
                : this.state.products.filter((prod) => prod.category === 'paint')
              }
            />
          </div>
        </div>
        <Footer />
      </div>
    );
  };
};

export default Archive;

我正在使用webpack捆绑我的项目,我的输入是:

const entry = [
    'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server and connect to the provided endpoint
    'webpack/hot/only-dev-server', // bundle the client for hot reloading only- means to only hot reload for successful updates
    './app.js'
]

..和我的dev-server.js文件看起来像这样:

var WebpackDevServer = require('webpack-dev-server');
var webpack = require('webpack');
// requiring my webpack configuration
var config = require('./webpack.config.js');
var path = require('path');

var compiler = webpack(config);
// then spinning up a new dev server with some settings
var server = new WebpackDevServer(compiler, {
    hot: true,
    filename: config.output.filename,
    publicPath: config.output.publicPath,
    proxy: {
        "/getMail": 'http://localhost:80/magdan/php/mailer.php',
        "/getProducts": 'http://localhost:80/magdan/php/products.php'
    },
    stats: {
        colors: true
    }
});

// its gonna listen to port 8080
server.listen(8080, 'localhost', function() {
    console.log("Starting server on http://localhost:8080");
});

我只会收到错误:

错误!!! JSON中位于位置0的意外令牌C

我非常感谢您的任何投入!

您的PHP文件未输出JSON。

您的提取处理程序正在调用res.json()

const data = await res.json();

期望输出格式正确的JSON,但是您的PHP文件输出“ Connected”:

echo "Connected successfully";

您需要更改PHP文件以返回有效的JSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM