在 useEffect 依赖数组中使用 Redux 状态时如何避免无限循环?

时间:2021-01-12 14:10:02

标签: javascript reactjs redux infinite-loop use-effect

我想弄清楚为什么我的 useEffect 函数会陷入无限循环。 我有两个变量连接到我的 Redux 商店:

const vehicles: AllVehiclesCollection = useSelector((state: ReduxState) => state.claims?.vehicles ?? {});
const properties: AllPropertiesCollection = useSelector((state: ReduxState) => state.claims?.properties ?? {});

而且我有一个动作被分派到商店,只有在用户点击按钮后才会更新这些动作。

我有一个 useEffect 会根据这些变量中的任何一个发生变化而触发。

useEffect(() => {
    let fullVehicleList: DropdownData[] = getFormattedVehicleListForDisplay();
    let fullPropertyList: DropdownData[] = getFormattedPropertyListForDisplay();
    let fullList = fullVehicleList.concat(fullPropertyList);
    if (fullList.length > 0) {
      setVehiclesAndPropertiesList(fullList);
    } else {
      setVehiclesAndPropertiesList(null);
    }
  }, [vehicles, properties]);

这段代码中没有任何地方改变了车辆或属性变量,也没有调度任何会改变 Redux 状态的动作。

getFormattedVehicleListForDisplay 函数:

const getFormattedVehicleListForDisplay = () => {
    let list: DropdownData[] = [];
    if (Object.keys(vehicles).length > 0) {
      let thisPolicysVehicles = [];
      if (vehicles !== null) {
        const key = `${selectedPolicy.symbol}${selectedPolicy.number}`;
        thisPolicysVehicles = vehicles[key];
      }
      if (thisPolicysVehicles && thisPolicysVehicles.length > 0) {
        thisPolicysVehicles.forEach((vehicle: VehicleInformation) => {
          if (vehicle.vehicleMake !== OTHER_VEHICLE) {
            list.push({
              label: formatVehicleForDisplay(vehicle),
              value: { ...vehicle, type: 'V' },
            });
          } else {
            list.push({ label: vehicle.vehicleMake, value: {} });
          }
        });
      }
    }
    return list;
  };

getFormattedPropertyListForDisplay 函数:

const getFormattedPropertyListForDisplay = () => {
    let list: DropdownDataOMIG[] = [];
    if (Object.keys(properties).length > 0) {
      let thisPolicysProperties = [];
      if (properties !== null) {
        const key = `${selectedPolicy.symbol}${selectedPolicy.number}`;
        thisPolicysProperties = properties[key];
      }
      if (thisPolicysProperties && thisPolicysProperties.length > 0) {
        thisPolicysProperties.forEach((property: LocationInformation) => {
          if (property.locStreet1 !== OTHER_PROP) {
            list.push({
              label: formatPropertyForDisplay(property),
              value: { ...property, type: 'P' },
            });
          } else {
            list.push({ label: property.locStreet1, value: {} });
          }
        });
      }
    }
    return list;
  };

作为参考,车辆和财产中的数据是一组键值对,其中键是给定帐号的唯一标识符,值是该帐户的车辆/财产对象数组。

知道为什么在依赖数组中使用 Redux 状态时会进入无限循环吗?是否有不同的方式在依赖数组中使用 Redux 状态?谢谢!

0 个答案:

没有答案