如何将参数传递给从自定义挂钩转换的函数?

How to pass the parameters to a function converted from custom hook?

我有一个自定义挂钩,它会在我的 Redux 切片“myTestSlice”中触发两个动作,action1 和 action2,在每个动作后面,我有 reducer 函数来获取新状态。

const useSetMyObjects = (
    actions,
    { object1Name, object1Id, object2Name, object2Id }, // here throws the error cannot read property of undefined when I call the function converted from this custom hook
) => {
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(actions.action1({ object1Name, object1Id }));
    }, [object1Name, object1Id, actions, dispatch]);

    useEffect(() => {
        dispatch(
            actions.action2({
                object2Name,
                object2Id
            }),
        );
    }, [object2Name, object2Id, actions, dispatch]);
};

export default useSetMyObjects;

我有一个 React 组件,我想在数组循环和事件处理程序中使用这个自定义挂钩。所以我必须把这个自定义钩子变成一个函数才能使用它,否则我会收到警告:

无法在回调中调用 React Hook“useSetMyObjects”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用

但我不知道如何将这个自定义挂钩转换为函数。

以下是我将如何使用从自定义挂钩转换而来的函数:

我想在 useEffect 中使用函数 setTwoObjects:

useEffect(() => {
        myData.map((data) =>
            useSetMyObjects(myTestSlice.actions, {//supposed to use that converted function instead of useSetMyObjects here, but no idea how
                object1Name: data.object1Name,
                object1Id: data.object1Id,
                object2Name: data.object2Name,
                object2Id: data.object2Id
            }),
        );
    }
}, [myData, useSetMyObjects]);

我还在事件处理程序中使用函数 setTwoObjects:

const handleSelect = (e, value) => {
        const newData = value;

        useSetMyObjects(myTestSlice.actions, {//supposed to use that converted function instead of useSetMyObjects here, but no idea how
            object1Name: newData.object1Name,
            object1Id: newData.object1Id,
            object2Name: newData.object2Name,
            object2Id: newData.object2Id,
        });
    }
};

如何将自定义挂钩转换为函数以便在回调或事件处理程序中调用它?

而不是 useSetMyObjects 挂钩接受参数,您希望挂钩 return 一个函数,该函数接受参数并将操作包装在对 dispatch 的调用中。

const useSetMyObjects = () => {
  const dispatch = useDispatch();

  const setTwoObjects = (
    actions,
    { object1Name, object1Id, object2Name, object2Id },
  ) => {
    dispatch(actions.action1({ object1Name, object1Id }));
    dispatch(actions.action2({ object2Name, object2Id }));
  };

  return setTwoObjects;
};

用法:

const setTwoObjects = useSetMyObjects();

...

useEffect(() => {
  myData.map((data) =>
    setTwoObjects(
      myTestSlice.actions,
      {
        object1Name: data.object1Name,
        object1Id: data.object1Id,
        object2Name: data.object2Name,
        object2Id: data.object2Id
      },
    )
  );
}, [myData, useSetMyObjects]);

...

const handleSelect = (e, value) => {
  const newData = value;

  setTwoObjects(
    myTestSlice.actions,
    {
      object1Name: newData.object1Name,
      object1Id: newData.object1Id,
      object2Name: newData.object2Name,
      object2Id: newData.object2Id,
    },
  );
};