【发布时间】:2020-06-06 16:05:16
【问题描述】:
我在 React Native 中使用 useEffect-hook 时遇到了一个特殊的问题。我有一个功能组件,它有一个 useEffect-hook 用于获取精确定位数据,另一个用于将精确定位 (filteredPinpoints) 重新排列为可用格式。 filteredPinpoints 更新了 3 次,但是前两次,对象是空的。
现在奇怪的行为:如果我在第二个 useEffect 中注释掉 dispatch(organiseRoutes(...)),这个 useEffect 会被调用 3 次,但是如果我想执行 dispatch 函数,useEffect 只会被调用两次。如果filteredPinpoints 为空,我会提前返回,因此代码永远不会到达调度程序。
编辑:另外,当我实现dispatch(organiseRoutes(...)) 时,应用程序冻结,只显示(旋转的)ActivityIndicator,但让我无法再次导航到上一个屏幕。
我必须更改什么,以便每次更新 filteredPinpoints 时都会运行 useEffect?
import { View, ActivityIndicator } from 'react-native';
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getRouteData, organiseRoutes } from '../utils';
export default function RoutePreviewScreen() {
const dispatch = useDispatch();
const [loadingData, setLoadingData] = useState(true);
const currentRouteID = useSelector(state => state.currentRouteID);
const filteredPinpoints = useSelector(state =>
// Uses ObjectFilter from https://stackoverflow.com/questions/5072136/javascript-filter-for-objects/37616104
ObjectFilter(state.allPinpoints, pinpoint => pinpoint.Route_ID == state.currentRouteID)
);
const dispatch = useDispatch();
// This updates state.allPinpoints.
useEffect(() => {
(async function myFirstAsyncFunction() {
await dispatch(getRouteData(currentRouteID));
})();
}, [currentRouteID]);
useEffect(() => {
if (Object.keys(filteredPinpoints).length === 0) {
return
}
console.log("Could EXECUTE now!!")
// If the following line is commented out, the useEffect executes a third time.
// However, only in the third run, filteredPinpoints is not a empty object.
// If it is not commented out, it simply refuses to execute a third time.
dispatch(organiseRoutes(filteredPinpoints));
setLoadingData(false)
}, [filteredPinpoints]);
if (loadingData) { return (<View><ActivityIndicator/></View>)}
return(<ComponentUsingOrganisedRoutes/>)
【问题讨论】:
标签: javascript reactjs react-native react-hooks