【发布时间】:2021-04-07 05:01:26
【问题描述】:
我有一个简单的商店
import React, { createContext, useReducer } from "react";
import Reducer from "./UserReducer";
const initialState = {
user: {},
error: null
};
const Store = ({ children }) => {
const [state, dispatch] = useReducer(Reducer, initialState);
return (
<Context.Provider value={[state, dispatch]}>
{children}
</Context.Provider>
);
};
export const Context = createContext(initialState);
export default Store;
我已经用它包装了我的应用程序
<Store>
<ThemeProvider theme={Theme}>
<CssBaseline />
<Navbar />
<Wrapper>
<Profile />
</Wrapper>
</ThemeProvider>{" "}
</Store>
还有一些额外的设置,我的身份验证页面位于单独的包装器中,所以我也用 store 包装了它。
这是该包装器的代码(额外删除)。
import Store from "../../../context/Store";
export default function Wrapper({ children }) {
const classes = useStyles();
return (
<Store>
//different dumb containers opening
{children}
//different dumb containers closing
</Store>
);
}
现在当我尝试访问子组件中的上下文时,例如
import React, { useContext } from "react";
import { Context } from "../../../context/Store";
import { SET_USER } from "../../../context/UserTypes";
function SignUp(props) {
const [state, setState] = React.useState({ ...initialState });
const [userData, dispatch] = useContext(Context);
console.log(userData, dispatch, "check");
// rest of component
我收到以下错误
TypeError: undefined is not a function
我尝试在不解构的情况下记录 useContext 的结果,但它只有全局状态,但没有调度函数。
Reactjs 版本 = 17.0.1
更新:使用 Authenticator HOC 可以在外部访问调度,但不能在内部访问,因此这可能是放大问题。
我已经打开了放大回购的问题。
Unable to access dispatch from useContext from components wrapped withAuthenticator
【问题讨论】:
标签: reactjs jsx aws-amplify context-api use-context