将整个对象传递给Redux重新选择选择器,但仅当对象的一个属性发生更改时才更改它

5anewei6  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(77)

开始使用Reselect,有一件事我似乎找不到答案。
假设我有一个助手fn(getVehicleList),它执行一些繁重的计算,所以我不希望它重新运行太多次。我使用状态选择器来获取我需要的属性,比如:

const getVehicles = (state) => state.vehicles.vehicles;
const getVehicle = (state) => state.vehicles.vehicle;
const getUserId = (state) => state.auth.user.id;

字符串
然后我实现了createSelector

const getVehicles = createSelector(
  [getVehicles,
   getVehicle,
   getUserId],
  (vehicles, vehicle, id) => getVehicleList(
    vehicles,
    vehicle,
    id,
  ),
);


现在,vehicle返回一个具有多个字段的对象。如果这些字段中的任何一个发生更改,则对象也会发生更改,因此所有内容都将重新计算。有没有一种方法可以停止这种重新计算,直到id和只有车辆的id改变?
我试着为id做一个状态选择器,比如

const getVehicle = (state) => state.vehicles.vehicle.id;


但这对我不起作用,因为我需要整个车辆对象在我的助手fn中,而不仅仅是id。
提前感谢您的帮助!

tjrkku2a

tjrkku2a1#

您可以尝试以下操作:

const getVehicles = (state) => state.vehicles.vehicles;
const getVehicle = (state) => state.vehicles.vehicle;
const getUserId = (state) => state.auth.user.id;
const selectVhicleId = createSelector(
  [getVehicle],
  ({ id }) => id //return only the id
);
const selectVehicles = createSelector(
  [getVehicles, selectVhicleId, getUserId],
  (vehicles, vehicleId, id) =>
    getVehicleList(vehicles, { id: vehicleId }, id)
);

字符串
Here是关于如何在React中使用reselect的一些信息。
这里有一个例子,当vehicle.id改变(或任何其他依赖关系)时,重新计算车辆。如果车辆的其他值发生变化,它将不会重新计算,因此车辆使用getVehicleList获得传递给它的过时车辆,该车辆仅在vehicle.id发生变化时刷新:

const getVehicles = (state) => state.vehicles.vehicles;
const getVehicle = (state) => state.vehicles.vehicle;
const getUserId = (state) => state.auth.user.id;
const createSelectVehicles = (vehicle) =>
  createSelector([getVehicles, getUserId], (vehicles, id) =>
    getVehicleList(vehicles, vehicle, id)
  );

const Component = () => {
  //only re calculate vehicle if vehicle.id changes
  const vehicle = useSelector(
    getVehicle,
    (a, b) => a?.id === b?.id
  );
  //only create the selector when vehicle changes
  //  vehicle only changes when vehicle.id changes
  const selectVehicles = React.useMemo(
    () => createSelectVehicles(vehicle),
    [vehicle]
  );
  //vehicles is re calculated when vehicle.id changes
  //  or when state.vehicles.vehicles changes or
  //  when state.auth.user.id changes
  const vehicles = useSelector(selectVehicles);
};

相关问题