如何使用useFocusEffect挂钩获取数据?

时间:2020-04-11 05:54:15

标签: javascript reactjs react-native react-hooks

我是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) 

请帮助

Error

1 个答案:

答案 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]));