React Context - 从函数调度

React Context - dispatch from a function

我必须在函数中调用 dispatch (Context, not Redux),但我做不到。 (Error: Invalid hook call. Hooks can only be called inside of the body of a function component.)

有没有办法在从组件调用的函数中 运行 挂钩(或仅 dispatch)? 我可以使用 Redux (store.dispatch(...)) 做到这一点,但我不知道如何使用 React Context 做到这一点。

示例函数:

function someAction() {
  const { dispatch } = React.useContext(SomeContext);
  dispatch({
    type: "ACTION_NAME",
  });
}

我正在尝试直接从组件调用该函数:

<button onClick={() => someAction()}>Click me</button>

当然,我可以通过dispatch,但我想避免这种情况,因为功能将被共享,并且应该很简单。

<button onClick={() => someAction(dispatch)}>Click me</button>

只能在组件中使用钩子或其他钩子,但可以在其他函数内部使用钩子的return值。从函数中提取 useContext,并使用 returned dispatch:

const Component = () => {
  const { dispatch } = React.useContext(SomeContext);

  function someAction() {
    dispatch({
      type: "ACTION_NAME",
    });
  }

  return (
    <button onClick={someAction}>Click me</button>
  );
};

我会创建一个 return 动作函数的自定义挂钩,并在组件中使用它,以使其不那么笨重且更可重用:

const useAction = () => {
  const { dispatch } = React.useContext(SomeContext);
  
  return () => dispatch({
    type: "ACTION_NAME",
  });
};

用法:

const Component = () => {
  const someAction = useAction();
  
  return (
    <button onClick={someAction}>Click me</button>
  );
};