gpt4 book ai didi

reactjs - 在 api 获取请求失败后重新调用 useEffect

转载 作者:行者123 更新时间:2023-12-04 16:40:54 25 4
gpt4 key购买 nike

我正在执行 useEffect() 以使用 JSON 数据更新状态。但是,获取请求有时会失败,因此如果发生这种情况,我想重新执行 useEffect 钩子(Hook):

...
import React, {useState, useEffect} from 'react';
import {getJsonData} from './getJsonData';

const myApp = () => {
var ErrorFetchedChecker = false;
const [isLoading,setIsLoading] = useState(true);
const [data,setData] = useState(null);

const updateState = jsonData => {
setIsloading(false);
setData(jsonData);
};

useEffect(() => {
//console.log('EXECUTING');
getJsonData().then(
data => updateState(data),
error => {
Alert.alert('DATA FETCHING ERROR !', 'Refreshing ?...');
ErrorFetchedChecker = !ErrorFetchedChecker;
//console.log('LOG__FROM_CountriesTable: Executed');
},
);
}, [ErrorFetchedChecker]);//Shouldn't the change on this variable
//be enough to re-execute the hook ?

return (
<View>
<Text>{state.data.title}</Text>
<Text>{data.data.completed}</Text>
</View>
);
}

这是 getJsonData() 函数以防万一:
export async function getJsonData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let responseJson = await response.json();
return responseJson;
} catch (error) {
throw error;
// Also, is this the correct way to handle the error ?
// As the Alert in useEffect goes off either ways.
// If not, advise me on how the error should be handled.
}
}

最佳答案

这将工作

const myApp = () => {
const [errorFetchedChecker, setErrorFetchedChecker] = useState(false);
const [isLoading,setIsLoading] = useState(true);
const [data,setData] = useState(null);

const updateState = jsonData => {
setIsloading(false);
setData(jsonData);
};

useEffect(() => {
//console.log('EXECUTING');
getJsonData().then(
data => updateState(data),
error => {
Alert.alert('DATA FETCHING ERROR !', 'Refreshing ?...');
setErrorFetchedChecker(c => !c);
//console.log('LOG__FROM_CountriesTable: Executed');
},
);
}, [errorFetchedChecker]);

return (
<View>
<Text>{state.data.title}</Text>
<Text>{data.data.completed}</Text>
</View>
);
}

关于reactjs - 在 api 获取请求失败后重新调用 useEffect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60872890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com