在我的 react-native 项目中,我有一个屏幕需要data
从后端查询,然后,有一些使用后端返回的代码data
应该只在屏幕安装时运行一次。这就是我所做的(我正在使用 [react-query][1] 从后端获取数据):
const MyScreen = ()=> {
// fetch data from backend or cache, just think this code gets data from backend if you don't know react-query
const {status, data, error} = useQuery(['get-my-data'], httpClient.fetchData);
// these code only need to run once when screen mounted, that's why I use useEffect hook.
useEffect(() => {
// check data
console.log(`data: ${JSON.stringify(data)}`);
// a function to process data
const processedData = processeData(data);
return () => {
console.log('Screen did unmount');
};
}, []);
return (<View>
{/* I need to show processed data here, but the processedData is scoped in useEffect hook & I need to have the process data function in useEffect since only need it to be run once */}
</View>)
}
我的问题:
中的代码useEffect
仅在安装屏幕时运行一次,但是此时上面的查询返回data
值undefined
,直到重新渲染发生,data
然后被提取但是里面的代码useEffect
将永远不会再次运行,尽管在重新渲染时获取了数据。我怎样才能摆脱这个问题?