我是React的新用户,在使用GraphQL创建一个简单的auth流程时出现问题,遵循React Router示例。
我希望/
成为我的登录屏幕,只有在用户退出时才会显示。如果没有,应用程序应重定向到/dashboard
(否则应该无法访问)。这就是我所拥有的,它在认证后生成无限循环:
class App extends Component {
constructor(props) {
super(props);
this.state = {
authenticated: false
}
}
renderButtons () {
if (this.state.authenticated) {
return (
<a>Logout</a>
)
}
return null;
}
componentWillReceiveProps({ data }) {
if (this.props.data.loading && !data.loading) {
if (data.loggedInUser.id && !this.state.authenticated) {
this.setState({authenticated: true});
} else if (this.state.authenticated) {
this.setState({authenticated: false});
}
}
}
render () {
return (
<div className="container">
<nav>
{this.renderButtons()}
</nav>
<GatingRoute path="/" component={LoginPage} isAuthenticated={this.state.authenticated} newPath="/dashboard" />
<PrivateRoute path="/dashboard" component={Dashboard} isAuthenticated={this.state.authenticated} />
</div>
);
}
};
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest}) => (
<Route
{...rest}
render={props => (
isAuthenticated
? (
<Component {...props} />
)
: (<Redirect to={{ pathname: '/', state: { from: props.location } }} />)
)}
/>
);
const GatingRoute = ({ component: Component, isAuthenticated, newPath, ...rest}) => (
<Route
{...rest}
render={props => (
isAuthenticated
? (
(<Redirect to={{ pathname: newPath, state: { from: props.location } }} />)
)
:
<Component {...props} />
)}
/>
);
export default graphql(query, { options: {fetchPolicy: 'network-only'}})(withRouter(App));
答案 0 :(得分:2)
而不是像现在这样工作......
在您拥有路线的父组件中,执行以下操作
<BrowserRouter>
<Route path=“/“ exact render={ ( props ) =>
props.user.loggedIn ? <Dashboard /> : <LoginForm />
}/>
</BrowserRouter>
这假定呈现路由器的组件知道用户状态。
我对移动设备上的格式不佳表示歉意。