[英]Call function of Context in react class component
I have following Code in my Context.js
:我的
Context.js
中有以下代码:
import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
isFetching: false,
error: false,
};
export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.user));
}, [state.user]);
return (
<Context.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</Context.Provider>
);
};
Now I want to use the Context in a class component and especially call the dispatch function, here a minimal example:现在我想在 class 组件中使用上下文,特别是调用调度 function,这里是一个最小的例子:
export default class Register extends Component {
static contextType = Context;
componentDidMount() {
const { dispatch } = this.context;
dispatch({ type: "LOGIN_START" });
}
render() {
return (
<div></div>
)
}
}
The Problem now is that dispatch
is undefined, when I want to call it inside my class. Before I used the same context with const { dispatch, isFetching } = useContext(Context);
现在的问题是
dispatch
是未定义的,当我想在我的 class 中调用它时。在我使用与const { dispatch, isFetching } = useContext(Context);
相同的上下文之前inside a functional component and everything worked fine, what is the problem?在功能组件内部,一切正常,问题是什么?
As suggested in one of the comments above, my ContextProvider
has to be an ancestor of my Register
component in the component tree.正如上面评论之一所建议的,我的
ContextProvider
必须是组件树中我的Register
组件的祖先。 I simply added it inside my index.js
:我只是将它添加到我的
index.js
中:
...
import { ContextProvider } from "./context/Context";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ContextProvider>
<React.StrictMode>
<App />
</React.StrictMode>
</ContextProvider>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.