基本上,我在react-router中有一个页面,该页面仅在用户被授权(this.state.authorized)时可用。如果未授权用户,则将他们重定向到主页。
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
authorized: false
}
this.handleLogin = this.handleLogin.bind(this);
this.handleLogout = this.handleLogout.bind(this);
this.rememberAuthorization = this.rememberAuthorization.bind(this);
}
rememberAuthorization() {
// if the key exists in localStorage
if (localStorage.hasOwnProperty("authorized")) {
// get the key's value from localStorage
let value = localStorage.getItem("authorized");
// parse the localStorage string and setState
try {
value = JSON.parse(value);
this.setState({ authorized: value });
} catch (e) {
// handle empty string
this.setState({ authorized: value });
}
}
}
handleLogin(username, password) {
if (username == "XXXX" && password == "XXXXXXXXXX") {
console.log(this.state.authorized)
this.setState({ authorized: true }, () => {
console.log(this.state.authorized)
localStorage.setItem("authorized", JSON.stringify(this.state.authorized))
})
}
else {
console.log("access denied")
}
}
handleLogout() {
this.setState({authorized: false}, () => {
//console.log(this.state.authorized)
localStorage.setItem("authorized", JSON.stringify(this.state.authorized))
console.log(this.state.authorized)
})
}
componentDidMount() {
this.rememberAuthorization();
}
render() {
return (
<Router>
<Route
exact path='/' render={(props) =>
<Search isAuthed={this.state.authorized} handleLogout={this.handleLogout} handleLogin={this.handleLogin} {...props} />
}
/>
<Route
exact path='/upload' render={(props) =>
<AddChar isAuthed={this.state.authorized} handleLogout={this.handleLogout} handleLogin={this.handleLogin} {...props} />
}
/>
<Route
exact path='/upload/success' render={(props) =>
<UploadConfirmation isAuthed={this.state.authorized} handleLogout={this.handleLogout} handleLogin={this.handleLogin} {...props} />
}
/>
</div>
</Router>
);
}
}
export default App;
this.state.authorized
作为对/upload
的支持而传递,这是授权用户无法通过URL地址进入的路由,但是可以通过以下链接进入主页:只有授权用户才能查看。
AddChar.js ("/upload")
render() {
let loggedIn = this.props.isAuthed
//localStorage.getItem("authorized");
console.log(`the loggedIn is ${true}`);
if (this.state.formSubmitted == true) {
return (<Redirect to="/upload/success" />)
}
else if (loggedIn) {
return (
//The regular page
);
} else {
console.log(`you're being redirected. the loggedIn is ${loggedIn}`)
return (<Redirect to="/" />) }
}
当我通过浏览器中的URL地址栏转到页面时,我被重定向,并且我的loggedIn
变量是true
,然后是false
。当我通过主视图上的链接转到页面时,console.log表示loggedIn
是true
。为什么我得到这个结果?无论我如何进入页面视图,我都应该不断登录。
检查(loggedIn === true)
是否作为查看页面的条件会重定向我,即使authorized: true
也是如此。如果我已注销,则可以通过URL地址栏访问/upload
。为什么页面的第一个渲染周期无法识别向下传递的道具的最新值?