簡體   English   中英

使用 ReactJS 獲取數據不顯示在瀏覽器上

[英]Fetch data keep not display on browser using ReactJS

我正在使用 ReactJS 和 MySql 作為我的數據庫創建一個簡單的獲取數據。 對於前端和后端之間的連接,我使用的是 express,數組數據出現在 console.log 中,但沒有出現在 html 頁面中,一切正常。

我添加了另一個 package “node-fetch”,但也無法正常工作。

這是我在 App.js 上的代碼

import React, { Component } from 'react';
import Navbar from '../src/components/Navbar';
import './App.css';
import fetch from 'node-fetch';

class App extends Component {
  constructor() {
    super();
    this.state = {
      tbl_barang: []
    };
  }

  componentDidMount() {
    fetch('http://localhost:4000')
      .then(res => res.json())
      .then(tbl_barang => this.setState({data: tbl_barang}, () => console.log('Customers fetched...', tbl_barang)));
  }

  render() {
    return (
      <div className='App'>
        <Navbar />
        <h1>Daftar Barang</h1>
        <ul>
        {this.state.tbl_barang.map(tbl_barang =>
          <li key={tbl_barang.id}>
            {tbl_barang.tipe_barang}
            {tbl_barang.product_name}
          </li>
        )}
        </ul>

        <button> Click disini </button>
      </div>
    );
  }
}

export default App;

這是從 MySQL 獲取數據的代碼

const path = require ('path');
const mysql = require ('mysql');

module.exports = function (app, connection) {
    //if no matching path, back to index.html
    app.get('/', function(req, res){
        connection.query('SELECT id, tipe_barang, product_name FROM tbl_barang', function (err, data){
            (err)? res.send(err):res.json ({data});
        })
    })
}

我希望在 html 頁面上顯示陣列數據

看起來您正在設置state.data而不是state.tbl_barang 要解決此問題,請更改您的componentDidMount()主體:

componentDidMount() {
    fetch('http://localhost:4000')
      .then(res => res.json())
      .then(tbl_barang => this.setState({tbl_barang: tbl_barang.data}, () => console.log('Customers fetched...', tbl_barang)));
}

您還可以更新您的組件以使用state.data屬性,這取決於您要使用的名稱。

通常你會想要兩個組件,App 和數據 map function 應該指向一個 Item 組件,你可以將道具傳遞給孩子。

因此,在您的渲染更改為...

  render() {
   return (
   <div className='App'>
    <Navbar />
    <h1>Daftar Barang</h1>
    {this.state.tbl_barang.map(tbl_barang =>
      <TableItem key={tbl_barang.id} tbl_barang={tbl_barang} />
    }
    )}

然后制作一個 TableItem 組件,我通常為這個組件制作一個單獨的文件。

const TableItem = ({ tbl_barang }) => {
    return (
        <div>
            {tbl_barang.tipe_barang}
            {tbl_barang.product_name}
        </div>
    )
}

export default TableItem;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM