我必须在函数中调用调度(Context,而不是Redux),但我不能这样做。(Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
)
是否有一种方法来运行钩子(或仅dispatch
)从组件调用的函数内?我可以使用Redux (store.dispatch(...)
)做到这一点,但我不知道如何用React上下文做到这一点。
示例函数:
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>
只能在组件或其他钩子中使用钩子,但可以在其他函数中使用钩子的返回值。从函数中提取useContext
,并使用返回的dispatch
:
const Component = () => {
const { dispatch } = React.useContext(SomeContext);
function someAction() {
dispatch({
type: "ACTION_NAME",
});
}
return (
<button onClick={someAction}>Click me</button>
);
};
我将创建一个返回action函数的自定义钩子,并在组件中使用它,以使它不那么笨拙,更易于重用:
const useAction = () => {
const { dispatch } = React.useContext(SomeContext);
return () => dispatch({
type: "ACTION_NAME",
});
};
用法:
const Component = () => {
const someAction = useAction();
return (
<button onClick={someAction}>Click me</button>
);
};