[英]Making sure that useState() hook has been updated by useEffect hook?
I refactored my code to use useEffect hook instead of using class, but I'm getting a memory leak on the refresh of my results.我重构了我的代码以使用 useEffect 挂钩而不是使用 class,但我在刷新结果时遇到了 memory 泄漏。 I did use useEffect but I still get a an error message, not sure where I'm making a mistake in my code.
我确实使用了 useEffect 但我仍然收到一条错误消息,不确定我的代码哪里出错了。
I get the following error:我收到以下错误:
Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument.
警告:State 来自 useState() 和 useReducer() 挂钩的更新不支持第二个回调参数。 To execute a side effect after rendering, declare it in the component body with useEffect().
要在渲染后执行副作用,请使用 useEffect() 在组件主体中声明它。
import React, { useEffect, useState} from 'react';
import { FlatList, View, TouchableHighlight } from 'react-native';
import { USANews } from '../components/fetchNews';
import Article from '../components/Article';
const homeScreen = ({ handleRefresh, navigation, }) => {
const [state, setState] = useState({articles: [], refreshing: true});
useEffect (() => {
fetchNews();
}, )
const fetchNews = () => {
USANews() .then(articles => {
setState({ articles, refreshing: false });
})
.catch(() => setState({ refreshing: false }));
};
handleRefresh = () => {
setState({ refreshing: true }, () => fetchNews());
};
return (
<View style={{backgroundColor: '#fffafa'}}>
<FlatList
data={state.articles}
keyExtractor={item => item.url}
refreshing={state.refreshing}
onRefresh={handleRefresh}
renderItem ={({item}) => {
return (
<TouchableHighlight onPress={() => navigation.navigate('Detail',
{title: item.title, description: item.description, urlToImage: item.urlToImage})}
>
<Article article={item} />
</TouchableHighlight>
);
}}
/>
</View>
);
}
export default homeScreen;
Remove the extra parameter from setState({ refreshing: true }, () => fetchNews())
in handleRefresh
.从
handleRefresh
中的setState({ refreshing: true }, () => fetchNews())
中删除额外参数。
Perhaps also add state
to a dependency array in the effect so it only runs when state
updates, unless you want the fetch to occur anytime the component renders.也许还可以将
state
添加到效果中的依赖项数组,这样它仅在state
更新时运行,除非您希望在组件呈现的任何时候进行提取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.