【发布时间】:2020-07-24 04:29:20
【问题描述】:
我已经创建了模块react-redux-area,但是模块文件中的hooks 不起作用。
在运行时我收到此错误:
could not find react-redux context value; please ensure the component is wrapped in a <Provider>
我看不出与其他类似的外部挂钩有任何真正的不同,所以我在尝试解决这个问题。 非常感谢任何帮助和建议。
export const useMyArea = () => {
const dispatch = useDispatch(); // <- No problem getting context here
useDispatchActions(myAreaActions); // <- This line DONT work!
useCreateActionDispatchers(myAreaActions); // <- This line work! (Another external hook)
// Debugging why provider dont works for useDispatchActions!
console.log(useDispatchActions.toString());
console.log(useCreateActionDispatchers.toString());
//const dispatchActions = useDispatchActions(myAreaActions);
//useDispatchActions(myAreaActions);
// This is the function that the useDispatchActions uses internally
// Which work fine then the dispatch is add as argument
const dispatchActions = CreateDispatchActions(dispatch, myAreaActions);
const areaState = useSelector((state: IStoreState) => state.myArea);
return {
...areaState,
...dispatchActions
};
};
模块代码:
模块在 gtihub 上: https://github.com/alfnielsen/react-redux-area/blob/master/ReactReduxArea.ts
const useDispatchActions = <T extends MapMethodWithActionName<T>>(
actionCreatorListObject: T
) => {
const dispatch = useDispatch()
const memoDispatchActionsObject = useMemo(
() => CreateDispatchActions(dispatch, actionCreatorListObject),
[dispatch, actionCreatorListObject]
)
return memoDispatchActionsObject
}
沙盒示例:
我有其他可以使用钩子的模块,在代码和框的示例中,我在应用程序钩子中使用它,没有问题。
(MyArea.ts 中的第 44 行不起作用,而相同类型的外部模块挂钩适用于第 45 行)
https://codesandbox.io/s/redux-area-base-ex-s5bg1?file=/src/MyArea.ts
【问题讨论】:
标签: reactjs typescript redux react-redux react-hooks