![](/img/trans.png)
[英]I'm fetching a problem when I'm trying to fetch data from an API by using useEffect in react
[英]I'm trying to fetch data from a server using useEffect react hook
我正在嘗試使用 fetch api 從服務器獲取數據並使用 uuidv4 作為鍵在無序列表中顯示此數據,我嘗試使用 react 的 useEffect 鈎子來執行此操作,但是,它獲取了數據,但隨后它說了我所有的鍵是相同的,我認為 useEffect 是原因,我嘗試添加一個空數組作為第二個參數以防止重新渲染,但隨后它說我缺少依賴項,當我將依賴項放入其中時,重新渲染並且 uuid 再次相同. 我不知道該怎么做我對鈎子比較陌生。
import React, { useState, useEffect } from "react";
import "./App.css";
const uuidv4 = require("uuid/v4");
function App() {
const [country, setCountry] = useState({
country: []
});
useEffect(() => {
console.log("fetching data");
fetch("http://localhost:5000/country")
.then(res => res.json())
.then(data => setCountry({...country, country: data }));
}, []);
return (
<>
<ul>
{country.country.map(item => {
return <li key={uuidv4}>{item.name}</li>;
})}
</ul>
</>
);
}
export default App;
我認為你必須調用它來生成 uuid:
return <li key={uuidv4()}>{item.name}</li>;
映射列表時分配或設置鍵的最佳方法是使用index
,您可以從 map 獲取
return (
<>
<ul>
{country.country.map((item, index) => {
return <li key={index}>{item.name}</li>;
})}
</ul>
</>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.