[英]_React$useContext is undefined on app.js component
I'm trying to useContext
on the file app.js
but I receive an error:我正在尝试在文件useContext
上使用app.js
,但收到错误消息:
_React$useContext is undefined _React$useContext 未定义
Normally, I wrap correctly the only component I have, but it tells it's undefined (I saw few answers before asking, some of them tells it's because of wrap problem).通常,我正确包装了我拥有的唯一组件,但它告诉它是未定义的(我在询问之前看到的答案很少,其中一些告诉它是因为包装问题)。 How should I approach the error?我应该如何处理错误?
import React from "react";
import "./App.css";
import UserProfile from "./components/UserProfile";
import UserContextProvider from "./contexts/UserContext";
// create method toggleStatus that will change the
// status value from true to false. keep in mind that this method has
//to be created before our state!
// create 2 properties for state: status (boolean)
//and toggle (toggleStatus method previously created)
// pass the whole state to the provider as a value
function App() {
function toggleStatus() {
updateUserValue(!userValue);
}
return (
<UserContextProvider>
<UserProfile />
</UserContextProvider>
);
}
};
export default App;
In your example you're trying to access the context outside of the provider.在您的示例中,您尝试访问提供程序之外的上下文。
All context consumers must be a descendant of a provider.所有上下文消费者必须是提供者的后代。 Look at this example: https://codesandbox.io/s/heuristic-hamilton-mfppv?file=/src/App.js看这个例子: https://codesandbox.io/s/heuristic-hamilton-mfppv?file=/src/App.js
In short, your useContext
must be used in a component that is a descendant of your UserContextProvider
.简而言之,您的useContext
必须在作为UserContextProvider
后代的组件中使用。
I usually create a custom hook on top of useContext
for my contexts that can help you find these errors:我通常在useContext
为我的上下文创建一个自定义钩子,可以帮助您找到这些错误:
function useMyContext() {
const context = React.useContext(MyContext);
if (!context) {
throw new Error('useMyContext must be used within a MyContextProvider');
}
return context;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.