【发布时间】:2021-10-23 16:48:22
【问题描述】:
我正在尝试使用 Axios 从 Django API 获取一些数据,并且当我只使用一次 useEffect(使用空数组 [] 调用它)时,它没有获取任何数据。但是,当我添加存储响应数据的状态时,它会进入无限循环并且每秒都在更改数据。我知道使用空数组调用 useEffect 只会调用一次,但它似乎不起作用。我怎样才能设法只获取一次数据?
我的代码:
function IdentificationStep(props) {
const [predictions, setPrediction] = useState([]);
const [loadingState, setLoadingState] = useState(true);
const [getValue , SetValue] = useState(true)
useEffect(() => {
setTimeout(() => {
setLoadingState(false);
}, 3000);
}, []);
const getPredictions = async () => {
const response = await axios.get('/snake-image/prediction/'+(props.id))
setPrediction(response.data)
}
useEffect(() => { getPredictions(); console.log(predictions); SetValue(false)}, [])
//infinite loop when i track predictions state
//useEffect(() => { getPredictions(); console.log(predictions); SetValue(false)}, [predictions])
我试过 .then(),就像 boxdox 向我建议的那样,但它仍然返回一个空数组
const getPredictions = async () => {
const response = await axios.get('/snake-image/prediction/'+(props.id)).then(response => {
setPrediction(response.data);
console.log(predictions);
})
//setPrediction(response.data)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
感谢帮助,我解决了
问题是使用效果一直在无限循环。我刚刚检查了我的预测状态的长度,然后在 useeffect() 上使用 if else 块
useEffect(() => {
async function getPredictions() {
let response = await axios.get('/snake-image/prediction/'+(props.id));
response = await response;
setPrediction(response.data);
setLoadingState(false);
console.log(response.data);
}
if(predictions.length < 3)
{
getPredictions();
console.log(predictions);
}
else{console.log("already done")}
}, [predictions])
【问题讨论】:
-
getPredictions返回一个承诺。你要么等待它,要么使用.then -
使用它但得到相同的结果可能我做错了什么??
-
以后,当您解决自己的问题时,请将您的解决方案作为答案发布,而不是编辑您现有的问题。
-
好的,谢谢你的提示
标签: javascript reactjs django-rest-framework axios use-effect