У меня проблема с проверкой длины моего состояния, хотя я использую 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 ? <>





Я считаю, что состояние 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;
}
ПРИМЕЧАНИЕ