我正在尝试基于身份验证呈现组件。如果用户未经过身份验证,则会将其重定向到登录页面。
无论我做什么,如果我直接转到/
路由,登录组件将继续呈现。
即使isAuthenticated
为真且视图重新渲染,我也无法渲染仪表板。我究竟做错了什么?是否有承诺?
class App extends React.Component {
constructor(props){
super()
this.state = {
isAuthenticated: false
}
}
componentWillMount(){
this.authenticate()
}
authenticate(){
fetch("http://localhost:3000/authenticated", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-type": "application/json"
},
body: JSON.stringify({
token: localStorage.getItem("token")
})
})
.then(res => res.json())
.then(data => {
if(data.success){
this.setState({ // Re-render
isAuthenticated: true
})
}
})
.catch(err => {
console.log(err);
});
}
render() {
return(
<Router>
<div id="container">
// First time false. After setState it's true.
{console.log("render", this.state.isAuthenticated)}
<Route exact path="/" render={() => {
// First time false. After setState, doesn't log.
console.log("auth", this.state.isAuthenticated);
return this.state.isAuthenticated
? <Dashboard />
: <Redirect to="/login"/>
}}/>
</div>
</Router>
)
}
}