Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在子组件中调用react context update函数?_Javascript_Reactjs_React Context - Fatal编程技术网

Javascript 如何在子组件中调用react context update函数?

Javascript 如何在子组件中调用react context update函数?,javascript,reactjs,react-context,Javascript,Reactjs,React Context,我正在尝试使用react上下文为我的react应用程序存储全局变量。我使用的是所有类组件,没有功能组件。我有一个登录表单,用户在其中输入他们的电子邮件和密码,我想使用上下文将电子邮件存储为全局变量。下面是我的UserContext文件 import React from "react"; export const UserContext = React.createContext(); export default UserContext; 然后在我的app.js中,我进

我正在尝试使用react上下文为我的react应用程序存储全局变量。我使用的是所有类组件,没有功能组件。我有一个登录表单,用户在其中输入他们的电子邮件和密码,我想使用上下文将电子邮件存储为全局变量。下面是我的UserContext文件

import React from "react";
export const UserContext = React.createContext();
export default UserContext;

然后在我的app.js中,我进行了以下设置:

class App extends Component {
  handleLoggedIn = (username) => {
    console.log("getting user: " + username);
    const user = { name: "deffy" };
    this.setState({ currentUser: user });
  };
  state = { currentUser: { name: null } };
  render() {
    return (
      <React.Fragment>
        <Nav />
        <div className="mainContent">
          <Switch>
            <UserContext.Provider
              value={{
                currentUser: this.state.currentUser,
                onLoggedIn: this.handleLoggedIn,
              }}
            >
              <Route path="/test" component={Test} />
              <Route path="/inventory" component={Inventory} />
              <Route path="/" exact component={Login} />
            </UserContext.Provider>
仅当电子邮件和密码的输入与数据库对匹配时,才应更改上下文名称变量的值。我在类组件之后也有这段代码

static contextType = UserContext;
任何帮助都将不胜感激

static contextType = UserContext;