【问题标题】:I can't use the value returned from promise我不能使用从 promise 返回的值
【发布时间】:2021-12-14 16:15:38
【问题描述】:

我编写代码从我的 api 获取数据。我第一次编写这个代码。

然后我得到结果。没关系

但在那之后我想使用那个值。我编码这个

它向我显示了错误。

我尝试阅读有关 promise 和 async 的内容,等待了很多,但对我没有帮助。请赐教。

import logo from "./logo.svg";
import "./App.css";
import React from "react";

function App() {
  const [stateData, setStateData] = React.useState("");
  const testGetData = async () => {
    const data = await fetch("/api/products/test").then((response) => {
      return response;
    });
    return data;
  };
 let productData = [];

 testGetData().then((response)=>{
   return response.json();
 }).then((res)=>{
    productData.push(res);
 });

console.log(productData);
console.log(productData[0].productName);
    
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>{stateData}</p>
      </header>
    </div>
  );
}

export default App;

【问题讨论】:

  • 请将代码粘贴到您的问题中,而不是使用屏幕截图。
  • productData 最初是一个空数组。所以productData[0] 不可用(undefined)。所以你正在尝试productData[0].productName,这意味着你正在尝试访问未定义的属性productName
  • 您需要使用setStateData(res) 而不是productData.push(res) 来导致重新渲染。您需要将fetchData() 调用放入useEffect 挂钩中。
  • 数据是异步的,所以你需要等到数据准备好,然后再尝试读取它。
  • 抱歉截图贴。下次我会避免截图询问。我将尝试 setState 以及如何等待数据准备好读取。

标签: javascript reactjs express mern


【解决方案1】:

首先你需要使用状态来存储请求中的数据

其次,要获取数据,需要将请求包装在 useEffect 中。你可以阅读更多关于它here

这是一篇很好的文章,描述了如何使用钩子https://www.robinwieruch.de/react-hooks-fetch-data异步获取数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 2018-01-20
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多