我知道這是一個常見問題,但在尋找答案數小時后,我決定尋求幫助。
我正在嘗試將狀態變數傳遞給組件,但該組件是在設定值之前呈現的
我的代碼:
import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import Seguradora from "../../components/seguradora/seguradora.component";
const CorretorasShow = () => {
const obj = useLocation();
const [names, setNames] = useState([]);
useEffect(() => {
const url =
"http://localhost:3001/corretoras/63338f415c502044e953d408"
obj.state._id;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setNames(json.seguradora); // <<<<<< setState
} catch (error) {
console.log("error", error);
}
};
fetchData();
}, []);
return (
<div>
<Seguradora props={names} /> //<<<<< state varible
</div>
);
};
我試過 useMemo、useRef 和三元運算子無濟于事。我不是專業程式員,而且我是 reactJS 新手,所以我可能對這些解決方法做錯了
uj5u.com熱心網友回復:
您需要添加names到useEffect依賴陣列并fetchData()僅在names為空陣列時呼叫。
useEffect(() => {
const url =
"http://localhost:3001/corretoras/63338f415c502044e953d408"
obj.state._id;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setNames(json.seguradora);
} catch (error) {
console.log("error", error);
}
};
names.length === 0 && fetchData();
}, [names]);
uj5u.com熱心網友回復:
由于names是一個陣列,您可以檢查該陣列是否已填充以有條件地呈現您的組件,如下所示:
return (
<div>
{ names.length > 0 ? <Seguradora props={names} /> : null}
</div>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521748.html
標籤:javascript反应
下一篇:獲取不包含特定鍵的物件
