【发布时间】:2017-07-17 19:31:53
【问题描述】:
尝试使用 React 进行身份验证。在我的 Login.js 文件中,我有我的 handleClick 函数,它获取 json(用于会话存储)和一个带有链接容器的提交按钮。现在在我的 index.js 文件中,我有一个带有替换的 requireAuth 函数。我的问题是 requireAuth 函数在我的 handleClick 之前触发。如何在我的 handleClick 之后触发它,以便 handleClick 在登录用户之前检查用户名和密码是否成功?现在它只是不会把我推到下一页。代码示例表示赞赏。我正在使用 React Router v3。
登录.js:
handleClick() {
fetch('/backend/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
})
.then(response =>{
if (response.ok) {
response.json().then(data => {
sessionStorage.setItem('loggedIn', data.success);
console.log('login success: ' + sessionStorage.getItem('loggedIn'));
});
}
else {
console.log('failed');
}
})
}
render () {
<LinkContainer to='/Dashboard'>
<Button onClick={this.handleClick} type="submit"> Submit />
</Button>
</LinkContainer>
}
index.js:
function requireAuth(nextState, replace) {
if (!(sessionStorage.getItem('loggedIn') === true)) {
console.log(sessionStorage.getItem('loggedIn'));
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
});
}
}
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Container}>
<IndexRoute component={Homepage}/>
<Route path="dashboard" component={Dashboard} onEnter=
{requireAuth}/>
</Route>
</Router>
【问题讨论】:
标签: javascript json reactjs authentication react-router