【问题标题】:The array data passed over is sent as a Promise how do I access it [duplicate]传递的数组数据作为 Promise 发送我如何访问它[重复]
【发布时间】:2021-06-19 06:02:43
【问题描述】:

我有一个通过 mongoose 连接到 mongoDB 的后端。我有一个控制器可以发送这样的用户数据

const db = require("../../auth/models");
const User = db.user


const addProduct = (req, res) => {

User.findOne({
    username: req.body.username
}, function(err, user) {
    if (err) {
        res.status(500).send({ message: err })
    }else{
      
        user.store.push({
  
            id: req.body.id, 
            barcode: req.body.barcode,
            productName : req.body.productName,
            price : req.body.price,
            quantity: req.body.quantity
        
        })
        user.save(function(err, newUser) {
            if (err) {
                res.status(500).send({ message: err });
            } else {
                console.log(newUser);
                res.status(200).send({ message: "Product updated successfully!!"})
            }
        })
    }
})



res.status(200).send({ message: "Product updated successfully!!"})
};

function currentUserStoreData  (req, res)  {
    User.findOne({
        username: req.body.username
        }, function(err, user) {
        if (err) {
            res.status(500).send({ message: err })
        }else{
          return( user.store )
        }
      
    });
  
};



const sendProducts = (req, res) => {
console.log(currentUserStoreData );
  res.status(200).send(currentUserStoreData )
}

const  inventory = {
    addProduct,
    currentUserStoreData ,
    sendProducts,



};

module.exports = inventory

user.store 是数组的形式 但控制台日志显示为未定义

然后是一个路由文件,其中包含一个POST 请求,用于将用户名发送到currentUserStoreData ,以及一个GET 请求,该请求获取currentUserStoreData 返回的数据,该数据被sendProductsData 捕获,并且路线看起来像这样

    const controller = require("../controller/inventory.controller")

module.exports = function(app) {
    app.use(function(req, res, next) {
      res.header(
        "Access-Control-Allow-Headers",
        "x-access-token, Origin, Content-Type, Accept"
      );
      next();
    });

    app.post('/api/inventory/currentUser', controller.currentUserStoreData );
     
    app.get('/api/inventory/getProductData', controller.sendProducts)
};

有一个服务文件可以像这样通过 axios 处理路由 从“axios”导入axios;

const user = JSON.parse(localStorage.getItem("user"));
const username = user.username

const API_URL = "http://localhost:8080/api/inventory/";

const addProduct = (id, barcode, productName, price, quantity) => {
    return axios.post(API_URL + "additem" , {
        username,
        id,
        barcode,
        productName,
        price,
        quantity,
    });
};

const currentUsername = () => {
 return axios.post(API_URL + "currentUser" , {
     username,
 })
}

const fetchProduct = () => {
    return axios.get(API_URL + "getProductData")
}

export default {
    addProduct,
    fetchProduct,
    currentUsername
};

当我从另一个文件导入它以通过数组映射时,我已经导入了服务文件 并像这样使用它

  import React from 'react'
import ProductService from "../services/product-service.js"
import Table from 'react-bootstrap/Table'
import {useState, useEffect} from "react";

 ProductService.currentUsername();

const createRow = (product) => {
  console.log(product);

    return (
      
    <tr>
        <td>{product.id}</td>
        <td>{product.barcode}</td>
        <td>{product.productName}</td>
        <td>{product.price}</td>
        <td>{product.quantity}</td>
    </tr>
    )
}
const InventoryTable = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    ProductService
      .fetchProduct()
      .then(data => setData(data));
  }, []);
    console.log(data);
    return (
      <div>
        <Table striped bordered hover variant="dark">
          <thead>
            <tr>
              <th>Id</th>
              <th>barcode</th>
              <th>Product Name</th>
              <th>Price</th>
              <th>Quantity</th>
            </tr>
          </thead>
          <tbody>
          {data.map(createRow)}
          </tbody>
        </Table>
      </div>
    );
    }
  

export default InventoryTable

现在我卡住了请帮忙 如果有什么需要在评论区提问

提前感谢您的帮助。

【问题讨论】:

  • store.then(result => )
  • 没有办法。您只能从 .then 回调中访问。这就是您使用异步代码的方式。

标签: javascript node.js reactjs mongodb express


【解决方案1】:

您不能在 React 组件的渲染中访问异步代码,因为渲染是一个完全同步的过程。

您可以访问返回的 Promise 并将结果本地保存到组件中。使用安装useEffect 挂钩访问获取服务并将解析的数据保存到本地状态。将状态映射到行。

import ProductService from "../services/product-service.js"

const InventoryTable = () => {
  const [data, setData] = React.useState([]);

  React.useEffect(() => {
    ProductService
      .fetchProduct()
      .then(data => setData(data));
  }, []);
  
  return (
    <div>
      <Table striped bordered hover variant="dark">
        <thead>
          <tr>
            <th>Id</th>
            <th>barcode</th>
            <th>Product Name</th>
            <th>Price</th>
            <th>Quantity</th>
          </tr>
        </thead>
        <tbody>
          {data.map(createRow())}
        </tbody>
      </Table>
    </div>
  );
};

【讨论】:

  • 我猜完整的 api 调用代码块应该在 useEffect 里面,而不仅仅是 promise resolve 函数。因为这样可以防止不必要的 api 调用组件重新渲染。
  • @RajdeepDebnath 代码每次安装只调用一次,但是是的,它不像写的那样直观。
  • 我明白,但我的数据数组在 Promise 中。我需要访问 Promise 中该数据中的信息,以便映射
  • @K.V.PraneethReddy 我不明白你的评论。您能否说明您需要在 data 中访问的内容以及您当时想要做什么?
  • @DrewReese 谢谢!所有的帮助。我从你所说的开始,最终解决了我的问题。我使用了 fetch() 函数,终于成功了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 2013-03-20
  • 2018-09-17
  • 2018-01-30
  • 2014-10-04
  • 2016-04-14
相关资源
最近更新 更多