我是React Native的新手,并且刚刚升级到react-navigation-5
我正在努力用新的钩子listener
替换旧的useFocusEffect
函数
这是旧功能:
const loadTrips = useCallback(async() => {
setError(null);
setIsRefreshing(true);
try {
dispatch(tripActions.fetchTrip());
} catch (error) {
console.log(error);
setError(error.message);
}
setIsRefreshing(false);
},[dispatch, setIsRefreshing, setError]);
*********************************************************
// This is the old function
useEffect(() => {
const willFocus = props.navigation.addListener(
'willFocus',
loadTrips
);
return () => {willFocus.remove();}
},[loadTrips]);
*********************************************************
useEffect(() => {
setIsLoading(true);
loadTrips().then(
setIsLoading(false),
);
}, [dispatch, loadTrips])
编辑1
我尝试将loadtrips
函数传递给useFocusEffect
,但显示错误
useFocusEffect(loadTrips)
请帮助
答案 0 :(得分:0)
您只需将loadTrips
函数传递给useFocusEffect
const loadTrips = useCallback(async() => {
setError(null);
setIsRefreshing(true);
try {
dispatch(tripActions.fetchTrip());
} catch (error) {
console.log(error);
setError(error.message);
}
setIsRefreshing(false);
},[dispatch, setIsRefreshing, setError]);
useFocusEffect(useCallback(() => loadTrips(), [dispatch, setIsRefreshing, setError]));