【发布时间】:2020-07-07 10:02:27
【问题描述】:
我正在执行 useEffect() 以使用 JSON 数据更新状态。但是获取请求有时会失败,所以如果发生这种情况,我想重新执行 useEffect 钩子:
...
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.
}
}
【问题讨论】:
-
useEffect 会在你的反应状态改变时再次运行,如果你的局部变量改变它不会再次运行。将 ErrorFetchedChecker 转换为反应状态。
-
props 也会导致重新渲染,因此 useEffect 将在 prop 更改时再次运行
-
确实如此,但是这里 ErrorFetchedChecker 的生命周期非常短,因为 react 不会在其堆栈中存储其他变量值。这就是使用 useState 的原因。
标签: reactjs react-native async-await fetch-api