[英]How can I make my React Component mount, when the right url is accessed and the user is not logged in?
My App.js:我的 App.js:
<Nav info={this.props}/>
{this.props.loading === true
? null
: <div>
{this.props.authedUser
? <Switch>
<Route path='/' exact component={Dashboard}/>
<Route path='/question/:id' exact component={QPage}/>
<Route path='/new' exact component={CreateQ}/>
<Route path='/leaderboard' exact component={Leaderboard}/>
<Route path='/sign-in' exact component={SignIn}/>
<Route component={Error}/>
</Switch>
: <Route path='/sign-in' component={SignIn}/>
}
</div>
}
My app shows a Nav bar at the top.我的应用程序在顶部显示了一个导航栏。 It has a button that says Logout .
它有一个按钮,上面写着Logout 。 When the button is clicked, I am clearing the authedUser behind the scenes in my Redux store and navigate to the '/sign-in' url.
单击该按钮后,我将在 Redux 商店中清除幕后的authedUser并导航到“/登录”url。 All of this works, but when the '/sign-in' url is accessed, my SignIn component doesn't get rendered.
所有这些都有效,但是当访问 '/sign-in' url 时,我的SignIn组件不会被渲染。 But when I reload, the SignIn component does get rendered.
但是当我重新加载时, SignIn组件会被渲染。
After the user is being logged out, App.js get re-rendered.用户退出后,App.js 会重新渲染。 Then the ternary operator should actually be false (because this.props.authedUser is null) and it should render the route and its component SignIn .
那么三元运算符实际上应该为 false(因为 this.props.authedUser 为空)并且它应该呈现路由及其组件SignIn 。 But this doesn't seem to happen.
但这似乎不会发生。 How can I make sure, that the SignIn component does get rendered, when the ternary operator returns false?
当三元运算符返回 false 时,如何确保SignIn组件确实被渲染?
When authedUser
is false app.js is re-render with out当
authedUser
为 false 时 app.js 会重新渲染
<Switch>
<Route path='/' exact component={Dashboard}/>
<Route path='/question/:id' exact component={QPage}/>
<Route path='/new' exact component={CreateQ}/>
<Route path='/leaderboard' exact component={Leaderboard}/>
<Route path='/sign-in' exact component={SignIn}/>
<Route component={Error}/>
</Switch>
so... when you navigate the user to /sign-in
the route those not exists所以...当您将用户导航到
/sign-in
那些不存在的路线时
In order to achive your goal, you can do this:为了实现您的目标,您可以这样做:
App.js
<Switch>
<Route path='/' exact component={Dashboard}/>
<Route path='/main' exact component={Main}/>
<Route path='/sign-in' exact component={SignIn}/>
<Route component={Error}/>
</Switch>
After a succesfull login, you will do history.push('/main'), and in Main.js all the authenticated routes will be managed成功登录后,您将执行 history.push('/main'),在 Main.js 中将管理所有经过身份验证的路由
Main.js
... your code...
if (!this.props.authedUser) {
return <Redirect to='/sign-in' />
};
return (
<Switch>
<Route path='/question/:id' exact component={QPage}/>
<Route path='/new' exact component={CreateQ}/>
<Route path='/leaderboard' exact component={Leaderboard}/>
</Switch>
)
and when you will want to navigate a user to some route:当您想要将用户导航到某个路线时:
history.push('/main/leaderboard')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.