gpt4 book ai didi

javascript - 引用错误 : Cannot access 'UserContext' before initialization - React

转载 作者:行者123 更新时间:2023-12-04 13:32:23 34 4
gpt4 key购买 nike

我正在尝试创建一个可供 React 应用程序中的所有类组件访问的 UserContext。我收到以下错误。

ReferenceError: Cannot access 'UserContext' before initialization
应用程序.js
import React, { createContext } from 'react';
export const UserContext = createContext(null);
function App() {
return (

<div className="App">
<UserContext.Provider value={null}>
<PageRoutes />
</UserContext.Provider>
</div>

);
}

export default App;
登录页面.js
import React, { Component } from 'react';
import { UserContext } from './App';

class MasterLoginPage extends Component {
static contextType = UserContext;
constructor(props) {
super(props);
this.state = {
username: null,
loggedIn: false
}

// logic to work with username, password authentication

render() {

return (
<div>
// logic for rendering login page
{
this.state.loggedIn &&
<UserContext.Provider value={this.state.username} />
}
</div>
}
}

MasterLoginPage.contextType = UserContext;

export default MasterLoginPage;
PageRoutes.js
import React from 'react';

export default () => (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={LoginPage} />
<Route exact path="/home" component={Home}/>
</Switch>
</BrowserRouter>
);
主页.js
import React from 'react';

export default class Home extends React.Component {
// I want to put this user in a state variable in this component
}
  • 为什么我已经在 App.js 中定义了引用错误?
  • 如果我必须将 userContext 值存储在其他类组件中的状态变量中,比如 Home.js,那么我该怎么做呢?
  • 最佳答案

    在渲染 block 中调用 UserContext。让我知道这是否有效

    关于javascript - 引用错误 : Cannot access 'UserContext' before initialization - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64256481/

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