3 回答

TA貢獻1934條經驗 獲得超2個贊
您不需要像 那樣跟蹤 API 調用的狀態。只需檢查輪詢是否存在,也可以創建一個新的狀態變量來跟蹤錯誤。const [found, setFound] = useState(1)
例如,這將呈現一個帶有“加載...”的 div當沒有數據時。請參閱下面的代碼,了解完整的解決方案,if (!poll) { return <div>Loading...</div>}
import React, { useEffect, useState } from 'react'
import axios from 'axios';
import { Redirect } from 'react-router-dom';
const Poll = (props) => {
const [poll, setPoll] = useState(null);
const [hasError, setHasError] = useState(false);
useEffect(() => {
axios.get(`api/poll/${props.match.params.id}`)
.then(res => {
console.log(res.data);
setPoll(res.data);
})
.catch(err => {
console.log(err.message);
setHasError(true)
});
}, [])
if(!poll) {
console.log('data is still loading')
return(
<div>Loading....</div>
)
}
if (hasError) {
console.log('error when fetching data');
return (
<Redirect to="/" push />
)
}
return (
<div>
{
poll && <div>/* The JSX you want to display for the poll*/</div>
}
</div>
);
}
export default Poll

TA貢獻1866條經驗 獲得超5個贊
在您的 than 中,嘗試使用過濾器:
setPoll(poll.filter(poll => poll.id !== id));
確保用您的識別器替換 id

TA貢獻1852條經驗 獲得超7個贊
標準方法是為加載和錯誤狀態設置其他變量,如下所示
const Poll = (props) => {
const [poll, setPoll] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
setLoading(true);
axios.get(`api/poll/${props.match.params.id}`)
.then(res => {
console.log(res.data);
setPoll(res.data);
})
.catch(err => {
console.log(err.message);
setError(true);
})
.finally(()=> {
setLoading(false);
};
}, [])
if(error) return <span>error<span/>
if(loading) return <span>loading<span/>
return (
<div>
// your poll data
</div>
)
}
添加回答
舉報