我必須在函式中呼叫調度(背景關系,而不是 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>
uj5u.com熱心網友回復:
只能在組件或其他鉤子中使用鉤子,但可以在其他函式內部使用鉤子的回傳值。從函式中提取useContext,并使用回傳的dispatch:
const Component = () => {
const { dispatch } = React.useContext(SomeContext);
function someAction() {
dispatch({
type: "ACTION_NAME",
});
}
return (
<button onClick={someAction}>Click me</button>
);
};
我將創建一個回傳操作函式的自定義鉤子,并在組件中使用它,以使其不那么笨重且更可重用:
const useAction = () => {
const { dispatch } = React.useContext(SomeContext);
return () => dispatch({
type: "ACTION_NAME",
});
};
用法:
const Component = () => {
const someAction = useAction();
return (
<button onClick={someAction}>Click me</button>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468926.html
