[英]React 16.7 protected routes
我想保护路由并使它们仅供经过身份验证的用户使用。 问题是我知道在执行fetch()之后是否对用户进行了身份验证并更新了上下文中的状态(这需要一些时间)
我想在获取完成并且上下文状态isAuthenticated = false时将用户重定向到/ login
import { Route, Switch } from 'react-router-dom'
import { MyContext } from './Context'
...
<MyContext.Consumer>
{(context) => (
<Switch>
<Route path="/" exact strict component={Homepage}/>
<Route path="/this-is-a-protected-route" exact strict component={Admin}/>
<Route path="/login" exact strict component={Login}/>
</Switch>
)}
</MyContext.Consumer>
这是背景
export const MyContext = React.createContext()
export class MyProvider extends Component {
state = {
'isAuthenticated': false,
}
componentDidMount() {
fetch('/authenticated')
.then(
function(response) {
response.json().then(function(data) {
this.setState({'isAuthenticated': true})
});
}
)
.catch(function(error) {
console.log('fetch error', error);
});
}
render() {
return (
<MyContext.Provider value={{
isAuthenticated: this.state.isAuthenticated
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
理想情况下,只有在点击/ this-is-a-protected-route并且state.isAuthenticated = false(但这是默认值!)之后,我才会被重定向到/ login。
为简洁起见,我删除了一些代码,以便我们可以专注于问题。 希望你理解,谢谢!
仅当用户通过身份验证时,才能呈现受保护的路由
{context.isAuthenticated ?
<Route path="/this-is-a-protected-route" exact strict component={Admin}/> :
<Redirect to='/login' />
}
专用路径可以移动到单独的组件。
这里有更多细节和例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.