盡管我使用 axios 獲取資料,但在檢查狀態長度時遇到問題。這是我到目前為止所做的。
代碼:
const getAllBanners = async () => {
res = await axios.get(`/admin_return_banner_positions/`).then((res) => {
setBanners(res.data.result)
})
}
// HANDLING USEEFFECT
useEffect(() => {
getAllBanners()
}, [])
{getBanners.hits.total.value > 0 ? <>
<thead>
<tr>
<th style={{ fontSize: "18px" }}>cat</th>
<th><span style={{ fontSize: "18px" }}>up</span><hr /><span> name</span></th>
<th style={{ fontSize: "18px" }}>number</th>
<th><span style={{ fontSize: "18px" }}>down</span><hr /><span>name2</span></th>
<th style={{ fontSize: "18px" }}>number</th>
</tr>
</thead> <> : null}
錯誤:
TypeError: Cannot read properties of undefined (reading 'total')
style={{ direction: "rtl", textAlign: "center" }}
738 | >
> 739 | {getBanners.hits.total.value > 0 ? <>
uj5u.com熱心網友回復:
我相信getBanners狀態已經用一些默認值初始化。該值可能沒有嵌套屬性高達total.
在這種情況下,您最好使用可選鏈接 -
const BannerComponent = () => {
const [getBanners, setBanners] = useState();
const getAllBanners = async () => {
await axios.get(`/admin_return_banner_positions/`).then((res) => {
setBanners(res.data.result)
});
}
useEffect(() => {
getAllBanners()
}, []);
if (getBanners?.hits?.total?.value > 0) { // <---- optional chaining
return (
<>
<thead>
<tr>
<th style={{ fontSize: "18px" }}>cat</th>
<th><span style={{ fontSize: "18px" }}>up</span><hr /><span> name</span></th>
<th style={{ fontSize: "18px" }}>number</th>
<th><span style={{ fontSize: "18px" }}>down</span><hr /><span>name2</span></th>
<th style={{ fontSize: "18px" }}>number</th>
</tr>
</thead>
<>
);
}
return null;
}
筆記
- 我已經對代碼進行了一些格式化以更好地理解它。
- 如果你不了解可選鏈,這里可以給你一個簡單的介紹 --> MDN
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475031.html
標籤:反应
下一篇:C 使用動態記憶體創建佇列
