You can try the following:
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 is some information about how I use reselect with React.
Here is an example that re calculate vehicles when vehicle.id changes (or any of the other dependencies). It will not re calculate if other values of vehicle change so the vehicle used getVehicleList gets a stale vehicle passed to it that is only refreshed when vehicle.id changes:
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);
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…