我想用登录创建一个React应用程序.为了维护用户状态,我想使用React 16.3引入的
Context API.在实施登录路由时,我遵循了
example in React Router documentation.
下面的源代码是(我希望)我的问题的一个非常简化的最小例子.当我在浏览器中打开localhost:3000 / protected时,URL会正确更改为localhost:3000 / login,但组件不会显示.似乎没有调用render()方法.
如何说服React渲染我的Login组件?
这是我的源代码.
App.js
import React, {Component} from 'react';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import Login from "./Login";
import Protected from "./Protected";
import ProtectedRoute from "./ProtectedRoute";
import UserContext from "./UserContext";
export default class App extends Component {
render() {
return (
<Router>
<UserContext.Provider value={false}>
<div>
<ProtectedRoute path='/protected' component={Protected}/>
<Route path='/login' component={Login}/>
</div>
</UserContext.Provider>
</Router>
);
}
}
Login.js
import React from 'react';
export default class Login extends React.Component {
render() {
return <p>Login</p>;
}
}
UserContext.js
import React from "react";
const UserContext = React.createContext();
export default UserContext;
ProtectedRoute.js
import React from 'react'
import {Redirect, Route} from "react-router-dom";
import UserContext from './UserContext';
const ProtectedRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={props =>
<UserContext.Consumer>
{loggedIn =>
loggedIn === true
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: {from: props.location}
}}/>
}
</UserContext.Consumer>
}
/>
);
export default ProtectedRoute;
Protected.js
import React from 'react';
export default class Protected extends React.Component {
render () {
return <h2>protected</h2>;
}
}
最佳答案 看起来这是一个错误:
https://github.com/ReactTraining/react-router/issues/6072,甚至可能是一个React错误:
https://github.com/facebook/react/issues/12551.
现在,您可以通过在单独的组件中呈现Router和您的上下文提供程序来解决它.像这样,例如:
const Routes = () => (
<UserContext.Provider value={false}>
<div>
<ProtectedRoute path='/protected' component={Protected}/>
<Route path='/login' component={Login}/>
</div>
</UserContext.Provider>
);
export default class App extends Component {
render() {
return (
<Router>
<Routes/>
</Router>
);
}
}