【问题标题】:Display table from SQL table in React在 React 中显示来自 SQL 表的表
【发布时间】:2019-01-21 15:01:38
【问题描述】:

我一直在尝试设置网站的后端,但在我使用 React 的前端尝试读取它时遇到问题。

设置

  • 我有一个包含属性(名称、价格、isBestSeller、isAvailable 等)的产品表。
  • 我正在阅读此表并使用 NodeJS 将数据发送到前端,如下代码所示:

`

const bodyParser = require('body-parser');
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const knex = require('knex')
const database = knex({
    client: 'pg',
    connection: {
      host : '127.0.0.1',
      user : 'username',
      password : '',
      database : 'databasename'
    }
  });
const app = express();
app.use(cors());
app.use(bodyParser.json());
database.select('*').from('products').then(data => {
    app.get('/', (req, res) => { 
        res.send(JSON.stringify(data));
    });
});
app.listen(3001);

`

这很好用,如果我 console.log 它我会得到正确的数据。 问题出现在前端,因为我还不太熟悉 fetch 和 promises。

在介绍后端之前,我从一个简单的 .js 文件中读取产品,该文件包含如下对象数组:

export const productsContent = [
  {
    boxImage: 'https://i.imgur.com/dn9ty6l.png', 
    boxTitle: 'Arabusta Arabica', 
    boxPrice: '€15', 
    discountPrice: '€9.99',
    bestSeller: false,
    available: false,
    description: 'Coming soon'
  },
   ...
]

现在我用这个替换了上面的代码:

export const productsContent = [
  fetch('http://localhost:3001')
  .then(function(response) { return response.json(); })
  .then(function(data) { 
    for (let i = 0; i < data.length; i++) {
      productsContentArray.push(data);

    }
  })
];

我在这里尝试做的是从后端获取对象数组并将其推送到常量 productsContent 并使用它来显示产品。

不幸的是,在.fetch 之外,我得到了我不确定如何解析的承诺,当我在 fetch 内部进行控制台时,我得到了正确的值。

有谁知道我如何正确解决 fetch 的承诺或如何从 fetch 函数之外的数据中获取价值?

【问题讨论】:

    标签: node.js reactjs fetch-api


    【解决方案1】:

    看起来你在正确的轨道上,但尝试将你的获取逻辑移到数组之外,类似于这个替代解决方案:

    const Products = {
         getContent() {
            return fetch(`http://localhost:3001/`, {
                headers: {
                    // header info here
                    // e.g. 
                    // "Content-type": "application/json",
                }
            }).then(res => {
                return res.json();
            }).then(jsonResponse => {
                return jsonResponse;
            });
        }
    }
    
    export default Products;
    

    然后,在您的前端,您可以执行以下操作:

    // other imports
    import Products from "./Products";
    
    // do other things
    
    const getProductResponse = Products.getContent();
    // handle productResponse status code
    console.log(getProductResponse);
    // do things with your data
    

    【讨论】:

    • 不幸的是,Products.getContent() 仍然像我的代码一样返回 Promise
    【解决方案2】:

    注意第 6 行 push(data) 中的 [i] 部分丢失了

    1| export const productsContent = [
    2|   fetch('http://localhost:3001')
    3|   .then(function(response) { return response.json(); })
    4|   .then(function(data) { 
    5|     for (let i = 0; i < data.length; i++) {
    6|       productsContentArray.push(data[i]);
    7|     }
    8|   })
    9| ];
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2016-04-08
      • 2021-01-20
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多