【问题标题】:React - auth won't work because of order of firing functionsReact - 由于触发功能的顺序,身份验证将不起作用
【发布时间】: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


    【解决方案1】:

    不要使用&lt;LinkContainer to='/Dashboard'&gt;,只需使用具有onCLick 功能的按钮即可。 当登录响应成功时,使用 react-router push,将用户发送到 'dashboard' 路由,如下所示。

    import { browserHistory } from 'react-router'; browserHistory.push('/some/path');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      相关资源
      最近更新 更多