簡體   English   中英

map 無法在 React 中首次渲染時獲取數據

[英]Can't map fetched data on first render in React

我有一個 API 返回我 4 個對象,我嘗試將它們保存在一個名為“產品”的新數組中,並將 map 保存到 DOM。 我的問題是 map function 在第一次渲染時不起作用。

如果我修改代碼中的某些內容,保存文件並再次查看 React 頁面,我會看到我的數據出現了。

我該如何解決?

import { useEffect, useState } from 'react';
import './App.css';

function App() {

  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("URL")
    .then(res => res.json())
    .then(data => {
      for(let i = 0; i < data.length; i++) {
        products.push(data[i])
      }
    })
  })

  console.log(products);

  return (
    <div className="App">
      {products.map((product,index) => (
        <div key={index}>{product.price}</div>
      ))}
    </div>
  );
}

export default App;

const [products, setProducts] = useState([]);

useEffect(() => {
    async function getdata() {      
      const res = await fetch("URL");
      const data = await res.json();
      setProducts(data)
    }

    let unmounted = false;    
    if (!unmounted) {
      getdata();
    }

    return () => unmounted = true;
}, []);

你可以試試這個,我希望它會起作用。

你直接改變 state 這是 React 的禁忌。

您需要改用setProducts state setter

useEffect(() => {
  fetch("URL")
    .then(async res => {
      if (!res.ok) { // don't forget to check for errors
        throw new Error(`${res.status}: ${await res.text()}`);
      }
      return res.json();
    })
    .then(setProducts) // pass the resolved data to the state setter
    .catch(console.error);
}, []); // use an empty dependency array to only run once on mount

這是一個使用JSONPlaceholder /albums API 的演示

編輯 romantic-galois-0jvkzt

首先,您在useEffect掛鈎中缺少依賴數組。 假設您希望useEffect掛鈎在初始渲染時運行,我將傳遞空依賴項數組 ( [] )。

下一個修復是您等待在產品中設置數據,如果設置了產品(即您有products.length > 0 ),則調用

useEffect(() => {
    fetch("URL")
    .then(res => res.json())
    .then(data => setProducts(data))
  }, [])

  console.log(products);

  return (
    <div className="App">
      {products.length && products.map((product,index) => (
        <div key={index}>{product.price}</div>
      ))}
    </div>
  );

您只需運行一次 useEffect() 然后您需要調用 setProducts

useEffect(() => {
    fetch("URL")
      .then(res => res.json())
      .then(data => {
        setProducts(data);
      })
  },[])

第一次渲染后獲取數據。 你可能想使用

{Boolean(products.length) && products.map((product,index) => (
    <div key={index}>{product.price}</div>
  ))}

useEffect(() => {
fetch("URL")
.then(res => res.json())
.then(data => {
  for(let i = 0; i < data.length; i++) {
    products.push(data[i])
  }
  setProducts(products);
})
})

反而

暫無
暫無

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

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