React:Authentification并避免重复代码组件

时间:2017-02-09 21:18:15

标签: javascript reactjs

我的所有主要反应组件都有这样的部分:

export default class ExampleMain extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isAuthenticated: Meteor.userId() !== null
        }
    }

    componentWillMount() {
        if (!this.state.isAuthenticated) browserHistory.push('/login')
    }
    componentDidUpdate() {
        if (!this.state.isAuthenticated) browserHistory.push('/login')
    }
}

有了这个,我正在检查用户是否已登录。如果这是假,则用户将被重定向到登录路由。 由于这部分用于许多组件,我在想是否可以优化它以获得干燥代码......

更新

我正在使用反应路由器:

render((
    <Router history={ browserHistory }>
        <Route path='/' component={ App }>
            <IndexRoute component={ Main } />
            <Route path='login' component={ Login } />
            <Route path='content/:id' component={ Content } />
        </Route>
        <Redirect from='*' to='/' />
    </Router>
), document.getElementById('root'))

2 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

<Router history={ browserHistory }>
    <Route path='/' component={ App }>
        <IndexRoute component={ Main } />
        <Route path='/login' component={ Login } />
        <Route path='content/:id' component={ Content } />
    </Route>
    <Redirect from='*' to='/' />
</Router>

在App中,使用withRouter“注入”组件内的路由器:

import { withRouter } from 'react-router';

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isAuthenticated: Meteor.userId() !== null
        }
    }

    componentWillMount() {
        if (!this.state.isAuthenticated) {
           this.props.router.push('/login');
        }
    }
}

export default withRouter(App);

答案 1 :(得分:1)

也许this会帮助你。我会尝试在路由之前使用任何钩子。但是,您总是可以使用that example

等功能扩展自己的类
function requireAuth(nextState, replace) {
  if (!auth.loggedIn()) {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

render((
  <Router history={ browserHistory }>
    <Route path='/' component={ App }>
      <IndexRoute component={ Main } />
      <Route path='login' component={ Login } />
      <Route path='content/:id' component={ Content } onEnter={requireAuth} />
    </Route>
    <Redirect from='*' to='/' />
  </Router>
), document.getElementById('root'))

要查看完整代码,请点击上面的链接。