我正在嘗試制作一個應用程式,我從 Graphql API 獲取資料,并在獲取后更新狀態,但在成功請求后,我獲取了資料,但無法使用該資料更新狀態。當我控制臺記錄回應資料時,它顯示具有所需資料的陣列,但是當我更新狀態和控制臺記錄狀態時,它顯示空陣列。
我需要更新狀態以在組件中使用它,當我這樣做時,它會拋出 currList 未定義的錯誤。
這是代碼和控制臺的圖片。
export default function App() {
const [search, setSeach] = useState("");
const [currList, setCurrList] = useState([]);
const fetchShips = async () => {
const response = await request(gql`
{
ships {
name
home_port
image
}
}
`);
console.log("request response", response.data);
setCurrList(response.data);
console.log("currlist:", currList);
};
useEffect(() => {
fetchShips();
}, [currList]);
const Searchitems = (event) => {
setSeach(event.target.value);
setCurrList(
currList.filter((item) => {
return item.name.includes(search) || item.home_port.includes(search);
})
);
};
return (
<div className="App">
<div className="container">
<header></header>
<div className="body">
<input
type="text"
id="search"
value={search}
onChange={Searchitems}
className="input"
placeholder="Search Ships"
/>
<p>Total Count: {currList.length}</p>
<div className="ships">
{currList.map((item, index) => {
return (
<Ship
key={index}
name={item.name}
port={item.port}
img={item.image}
/>
);
})}
</div>
</div>
</div>
</div>
);
}
uj5u.com熱心網友回復:
狀態不是在代碼運行時更新,這就是為什么它記錄狀態是一個空陣列的原因,再次嘗試 console.log 它,你會看到串列中有一些東西。
uj5u.com熱心網友回復:
這是正常的,一切都是異步發生的。一旦您的 currList 更新,React 將觸發重新渲染,您將獲得它的新值。如果你想聽這個變化,你必須使用 useEffect 和 currList 作為依賴項。
useEffect(() => {
console.log("List is updated", currList);
}, [currList]);
uj5u.com熱心網友回復:
fetchShips 函式關閉了與特定渲染呼叫相關的 currList 狀態變數,因此當您在呼叫 setCurrList 后記錄它時,它會向您顯示之前的狀態而不是更新的狀態,您可以將其記錄在 useEffect 中以查看更改。
uj5u.com熱心網友回復:
我曾經遇到過同樣的問題。我找不到有效的解決方案,但無論如何我的解決方案救了我。
我使用了 useRef 而不是 useState。試試這個:
const currList = useRef([]);
useEffect=(()=>{
const fetchShips = async () => {
const response = await request(gql`
{
ships {
name
home_port
image
}
}
`);
console.log("request response", response.data);
// setCurrList(response.data);
if(response)
currlist.current = response.data
console.log("currlist:", currList);
};
fetchShips()
// Also as far as I know ,you should use useEffect like this
},[])
//... codes
return(
//... codes
currList.current.map(...
)
//... codes
在使用 useRef 之前,請嘗試在 useEffect 中定義您的 fetchShips 函式,因此您可能不需要我的解決方案。
為什么我的解決方案對您的情況無效?當您想要更新 currList 資料時, useRef 不會觸發重新渲染。即使您的資料已更新,您也無法在螢屏上看到它。所以 setCurrList(currList.current) 可以拯救你,但正如我之前所說,它可能不是有效的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/386009.html
