根据ajax请求呈现重定向组件

时间:2017-08-18 19:35:59

标签: reactjs redux react-router react-redux react-router-v4

我有一条回家路线' /'每当用户前往该路线时,如果他经过身份验证,我都会将他发送到他的页面,或者将他发送到' / login'路线,如果他没有经过身份验证。为了将用户发送到他的页面,我向服务器发出请求,获取他的id并根据我从服务器获得的id将他重定向到路由。但是,我对如何正确地在我的Home组件中实现该逻辑感到有点困惑。根据ajax请求的结果呈现重定向组件的最佳方法是什么?

class Home extends React.Component {

    async componentDidMount() {
        const response = await Api.getUserId();
        const id = response.data._id;
    }  

    render() {
        if(this.props.userStatus.authenticated) {
            return <Redirect to={{
                pathname: `/${id}`,
                state: { from: this.props.location }
            }}/>
        }
        return <Redirect to={{
            pathname: '/login',
            state: { from: this.props.location }
        }}/>
    }
}

export default connectComponent(['userStatus'], Home);

2 个答案:

答案 0 :(得分:2)

你可以这样做: 创建一个名为PrivateRoute的新组件:

import React from 'react'
import { Redirect, withRouter, Route } from 'react-router-dom'
import { isLogin } from '../actions/actions_rents'
import { connect } from 'react-redux'

const PrivateRoute = ({ component: Component, ...rest }) => {
    return(
        <Route {...rest} render={props => (
        isAuthenticated ? (
        <Component />
        ) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }}/>
      )
    )}/>
  )
}

然后在你的App.js或者你有你的路线的地方,你调用PrivateRoute并在这种情况下作为道具传递组件Home:

<Switch>
  <Route path="/login" component={Login}/>
  <PrivateRoute path="/" component={IndexRents} />
</Switch>

另外,我建议您看一下这个例子: https://reacttraining.com/react-router/web/example/auth-workflow

答案 1 :(得分:0)

 fetch('//offline-news-api.herokuapp.com/stories')
.then(function (response) {
    console.log(response);
    const login = response.ok;
    class Entry extends React.Component {
        constructor(props) {
            super(props);
        }
        render() {
            return (
                <Router>
                    <Switch>
                        <Route exact path="/login" component={Login}/>
                        <Route path="/" render={() => (
                          login ? (
                              <Common/>
                          ) : (
                            <Redirect to="/login"/>
                          )
                        )}/>
                    </Switch>
                </Router>
            );
        }
    }

    ReactDOM.render(<Entry/>, document.getElementById('root'));

})
.then(function (stories) {
});