反应:异步和等待不使用提取

新手上路,请多包涵

我在节点服务器上有 API,在调用时返回这样的 JSON:

 {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuantity":100}]}

我正在尝试使用带有 React 的获取 API 向用户显示所有这些信息,但无论我的调用返回什么 undefined 。这是我的 React 代码:

 const [products, setProducts] = useState({})

async function getProducts() {
    await fetch(`http://127.0.0.1:5000/listProducts`)
    .then(response => response.json())
    .then(response=>{
      setProducts({products:response.result})
      console.log(response.result);
      products.map(products =>
        <h1>{products.ProductName}</h1>
        <h1>{products.ProductDescription}</h1>
        )
    })
    .catch(err=>console.error(err))
  }

加载页面时调用函数 getProducts() 一次。我做错了什么?提前致谢。

原文由 Mr. Engineer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 234
2 个回答

你的功能做错了:

  • The name should be getAndSetProducts or even setProducts / initProducts because it returns a Promise<void> since you don’t actually return anything ;
  • 你在里面设置 products 一个对象 { products: Product[] } ,我想你只想要 Product[] (一系列产品)你会 products.products ;
  • 地图是无用的,因为你不对地图响应做任何事情,再加上地图中的变量 products 覆盖导入的那个(以后可能会导致一些错误)。

试着做 :

 const [products, setProducts] = useState([]); // Array instead of object

async function initProducts() {
    await fetch(`http://127.0.0.1:5000/listProducts`)
        .then(response => response.json())
        .then(response => {
            setProducts(response.result);
            console.log(response.result);
        )
        .catch(err => console.error(err));
}

function getProductsHtml() {
    return products.map(product =>
        <h1>{product.ProductName}</h1>
        <h1>{product.ProductDescription}</h1>
    );
}

您可以在组件初始化时调用 initProducts 并在 jsx 渲染中返回 getProductsHtml

原文由 Robin Michay 发布,翻译遵循 CC BY-SA 4.0 许可协议

试试这个它会工作

const handleFetchData = async () => {
    const response = await fetch(`https://api.unsplash.com/photos/random?client_id=${process.env.NEXT_PUBLIC_UNSPLASH_API_ACCESS_KEY}`);
    const data = await response.json();
    console.log(data);
}

useEffect(() => {
    handleFetchData();
},[])

原文由 Labhansh Satpute 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题