我试图创建一个UserContext以便React应用程序中的所有类组件都可以访问。我收到以下错误。
ReferenceError: Cannot access 'UserContext' before initialization
App.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;
LoginPage.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>
);
Home.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
}
答案 0 :(得分:0)
在渲染块中调用UserContext。让我知道这是否有效
答案 1 :(得分:0)
我建议创建一个组件来直接包装路由:
WithUser.jsx
import React, { createContext } from 'react';
const UserContext = createContext(null);
export default (props) => {
<UserContext.Provider value={null}>
{ props.children }
</UserContext.Provider>
};
然后:
PageRoutes.jsx
import React from 'react';
export default () => (
<BrowserRouter>
<Switch>
<WithUser>
<Route exact path="/login" component={LoginPage} />
<Route exact path="/home" component={Home}/>
</WithUser>
</Switch>
</BrowserRouter>
);
如果您想让两个路由都可以使用 Context,如果没有,只需包装您想要使用的那个。
答案 2 :(得分:0)
该错误似乎是由循环依赖引起的。我为解决该错误所做的是在 Provider 文件之外创建上下文。尝试这样做:
UserContext.js
import React from 'react';
export const UserContext = React.createContext();
登录页面.js
static contextType = UserContext;
或
MasterLoginPage.contextType = UserContext;
两者都不是。
你唯一需要做的就是导入 UserContext.js