React js重定向节流历史记录状态更改

时间:2018-07-14 02:21:31

标签: javascript reactjs authentication react-router

在成功登录后尝试执行重定向到私有路由,并从API获取身份验证令牌并将其存储在sessionStorage中。在我的主要App组件中,我正在使用Switch:

<Switch>
    <Route exact path='/' component={Home} />
    <Route path='/login' component={Login} />
    <PrivateRoute path='/cpanel' component={Cpanel} />
</Switch>

私人路线的定义如下:

const PrivateRoute = ({ component: Component, ...rest }) => (

   <Route { ...rest } render = {(props) => (
       sessionStorage.getItem('authToken') === true
         ? <Component { ...props } />
         : <Redirect to='/login' />
    )} />
);

在我的Login组件中,handleSubmit函数如下:

handleSubmit(event) {

    // preventing default form behaviour from submitting..
    event.preventDefault();

    // extracting form data and resetting form fields..
    const form = event.target;
    const data = new FormData(form);
    form.reset();

    // send post request to API..
    axios.post(this.state.uri, {
        email: data.get('email'),
        password: data.get('password')
    })
        .then((response) => {
            // save authorization token in client side..
            sessionStorage.setItem('authToken', response.data.id);
            this.setState({ token: response.data.id });
            console.log('Login successful! Authorization token id: ' + sessionStorage.getItem('authToken'));
            this.props.history.push('/cpanel');
        }).catch((error) => {
            console.log(error);
        });

}

我想这与'this.props.history.push()'有关,因为在我的Login组件的render方法中,我在返回JSX之前放了这段代码:

if (sessionStorage.getItem('authToken')) {
    return <Redirect to='cpanel' />
} else {
    console.log('Your authorization token is not set..');
}

我非常感谢任何回答,因为我已经尝试了2天来自行解决此问题。提前致谢!你们都有美好的一天!

0 个答案:

没有答案