gpt4 book ai didi

javascript - 单击处理程序中未定义 react 上下文值

转载 作者:行者123 更新时间:2023-12-05 08:05:58 24 4
gpt4 key购买 nike

我有一个功能组件,我试图在其中使用上下文,我在导入过程中获得了值,但是当我想在点击处理程序中使用它时,却说它未定义

component.js

// I get these values over here
const [contextState, setContextState] = useContext(MyContext);
const clickHandler = (e) => {
debugger; // when I am trying to log any of these values I get error of not defined
}

return (<button onClick={clickHandler}>Click me!</button>);

此外,我已经包装了我的 app.js 组件,如下所示

import { MyContextProvider } from './MyContext';
return (
<Router>
<MyContextProvider>
<div className='App'>
<Component />
</div>
</AuthContextProvider>
</Router>
);

现在是我的上下文文件,myContext.js

import React, { useState, createContext } from 'react';

const MyContext = createContext([{}, () => {}]);

const MyContextProvider = (props) => {
const [contextState, setContextState] = useState({
userIsLoggedin: false,
fName: '',
lName: '',
userName: ''
});
return (
<myContext.Provider value={[contextState, setContextState]}>
{props.children}
</myContext.Provider>
);
};

export { myContext, MyContextProvider };

最佳答案

看起来您的上下文文件中有一些拼写错误。首先,使用 MyContext该文件中的任何地方(不是 myContext ),其次,请注意您在第一次调用时指定的变量名称 useState然后将相同的值传递给上下文( authStatecontextState ):

import React, { useState, createContext } from "react";

const MyContext = createContext([{}, () => {}]);

const MyContextProvider = props => {
const [authState, setAuthState] = useState({
userIsLoggedin: false,
fName: "",
lName: "",
userName: ""
});
return (
<MyContext.Provider value={[authState, setAuthState]}>
{props.children}
</MyContext.Provider>
);
};

export { MyContext as default, MyContextProvider };

Here's a working codesandbox with your setup

关于javascript - 单击处理程序中未定义 react 上下文值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62640040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com