[英]React Context API - Consuming context inside a function, undefined error
I'm trying to create a global variable that holds false and true when the user switches between view1 and view2.我正在尝试创建一个全局变量,当用户在 view1 和 view2 之间切换时,该变量保持 false 和 true。 I want to use the Context API to create this global variable with a separate Context.js file that holds the Context and Providers, wrap the components in the App.js file, and consume the context by getting the value of the variable in a function in the appropriate components.
我想使用 Context API 通过一个单独的 Context.js 文件创建这个全局变量,该文件包含 Context 和 Providers,将组件包装在 App.js 文件中,并通过在 function 中获取变量的值来使用上下文在适当的组件中。 I tried following tutorials but I keep getting a displayContext is not defined error, where am I going wrong?
我尝试了以下教程,但我一直收到 displayContext is not defined 错误,我哪里出错了?
Context.js上下文.js
import React, {createContext, useState} from "react";
const viewContext = createContext();
const viewProvider = ({children}) => {
const[display, setDisplay] = useState(true);
return(
<viewContext.Provider value = {display}>
{children}
</viewContext.Provider>
);
};
export {viewProvider};
App.js应用程序.js
import React from "react";
import Session from "./components/Session";
import Map from "./components/Map";
import Navbar from "./components/Navbar";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./App.css";
import { viewProvider } from "./components/Context";
const App = () => {
return (
<viewProvider>
<Router>
<div className="App">
<Navbar />
<Routes>
<Route path="/" exact element={<Map />} />
<Route path="/session" element={<Session />} />
</Routes>
</div>
</Router>
</viewProvider>
);
};
export default App;
Map.js Map.js
import React, {useContext} from "react";
function Map(){
const display = useContext(viewContext);
console.log("the value of display is", {display});
return(
<div>
//some stuff
</div>
};
}
You need to export viewContext from your Context file:您需要从上下文文件中导出 viewContext:
export const viewContext = createContext();
and import it into your Map.js file:并将其导入到您的 Map.js 文件中:
import { viewContext } from 'Context'
You should also provide setDisplay as value in your Context.js:您还应该在 Context.js 中提供 setDisplay 作为值:
<viewContext.Provider value={[display, setDisplay]}>
{children}
</viewContext.Provider>
Which would necessitate changing这将需要改变
const display = useContext(viewContext)
to到
const [display] = useContext(viewContext)
in Map.js在 Map.js
import React, {useContext, useState} from "react";
export const defaultSpeedDialContext = [true, () => {
}];
const SpeedDialContext = React.createContext(defaultSpeedDialContext)
export default SpeedDialContext;
export function SpeedDialContextContainer({children}) {
const [visibility, setVisibility] = useState(defaultSpeedDialContext.visibility)
return (
<SpeedDialContext.Provider
value={[
visibility,
setVisibility
]}>
{children}
</SpeedDialContext.Provider>
)
}
export function useSpeedDialContext() {
return useContext(SpeedDialContext)
}
And you can use useSpeedDialContext() in your component您可以在组件中使用 useSpeedDialContext()
if you can use redux... its very easy for you, do this. npm install @reduxjs/toolkit --save npm install react-redux --save INDEX.js reducer.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; //Redux import { Provider } from 'react-redux'; // provider ekt wad import { configureStore } from '@reduxjs/toolkit'; import userReducer from './Redux_State_Mangement/Reducer_Actions'; const store = configureStore({ reducer: { userFromIndexjs: userReducer }, }) ReactDOM.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode>, document.getElementById('root') ); //Reducers.js import { createSlice } from '@reduxjs/toolkit' export const userSlice = createSlice({ name: ""user"", initialState: { //pass krn data obj ek hadagatta value: { name: ""savindu pasintha"", age: """", email: """" }, loginData: { name: """", age: """", email: """" }, profileData: { name: """", age: """", email: """" }, fetchAllData: [{ name: """", age: """", email: """" }] }, reducers: { login: (state, action) => { state.value = action.payload }, loginDataAction: (state, action) => { state.loginData = action.payload }, profileDataAction: (state, action) => { state.profileData = action.payload }, fetchAllDataAction: (state, action) => { state.fetchAllData = action.payload }, } }) //export actions to use in login.js file or we export const { login, loginDataAction, profileDataAction, fetchAllDataAction } = userSlice.actions; //index.js eke reducer export default userSlice.reducer;" Profile.js import React from 'react'; import { useSelector } from 'react-redux'; export default function Profile() { //index.js eke reduser ekekn userFromIndexj ekaccess krn ek //-> features eke initial stste eke value kiyn obj ek const dataObj = useSelector((state) => state.userFromIndexjs.value); return ( <div>Profile <div> <h1>Name: {dataObj.name}</h1> <h1>Age:{dataObj.age} </h1> <h1>Email: {dataObj.email}:</h1> </div> </div> ) }" //Login.js import React from 'react'; import { useDispatch } from 'react-redux'; import { login } from '../Reducer_Actions'; export default function Login() { const dispatch = useDispatch(); //dispatch({ name: ""kamal"", age: ""20"", email: ""ex@gmail.com"" }); return ( <div>Login page <div> <button onClick={() => { dispatch(login({ name: ""kamal"", age: ""20"", email: ""ex@gmail.com"" })); }}>Login</button> </div> </div> ) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.