React-Router v4 onEnter replacement

时间:2017-04-10 01:43:52

标签: reactjs react-router redux-thunk

I'm currently trying to build a simple react-redux app that has student and campus data in the backend. OnEnter used to work here, but it doesn't exist in the new react-router.

This app tries to load initial data at the start instead of doing a componentDidMount in each actual component. Is that the recommended approach, or are there alternative patterns that I'm not aware of?

/* -------------------<    COMPONENT   >------------------- */
import React from 'react';

import { BrowserRouter as Router, Route } from 'react-router-dom';
import Home from './components/Home';
import Students from './components/Students';

const Routes = ({ getInitialData }) => {
  return (
    <Router>
      <div>
        <Route exact path="/" component={Home} onEnter={getInitialData} />
        <Route path="/students" component={Students} />
        <Route path="*" component={Home} />
      </div>
    </Router>
  );
};

/* -------------------<   CONTAINER   >-------------------- */

import { connect } from 'react-redux';
import receiveStudents from './reducers/student';
import receiveCampuses from './reducers/campus';

const mapState = null;
const mapDispatch = dispatch => ({
  getInitialData: () => {
    dispatch(receiveStudents());
    dispatch(receiveCampuses());
  }
});

export default connect(mapState, mapDispatch)(Routes);

4 个答案:

答案 0 :(得分:19)

我目前的解决方案是在渲染功能中添加额外的代码,而不是使用组件属性。

<Route exact path="/" render={() => {
    getInitialData();
    return <Home />;
} } />

答案 1 :(得分:11)

我想建议一些不同的方法。使用类继承,您可以实现自己的路由器。

import {Redirect, Route} from 'react-router';



/**
 * Class representing a route that checks if user is logged in.
 * @extends Route
 */
class AuthRequiredRoute extends Route{
  /**
   * @example <AuthRequiredRoute path="/" component={Products}>
   */
    render() {
        // call some method/function that will validate if user is logged in
        if(!loggedIn()){
            return <Redirect to="/login"></Redirect>
        }else{
          return <this.props.component />
        }
    }
}

答案 2 :(得分:8)

一种解决方案是使用HOC

function preCondition(condition, WrappedComponent) {
   return class extends Component {
     componentWillMount{
          condition()
     }

      render() {
          <WrappedComponent {...this.props} />
      }
    }
}

<Route exact path="/" component={preCondition(getInitialData, Home )} />

答案 3 :(得分:0)

import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom';

class LoginRoute extends Component{
    render() {
        const isLogin = () => {
            if () {
                return true;
            }
            return false;
        }
        if(!isLogin()){
            return <Redirect to="/login"></Redirect>
        }else{
            return <Route path={this.props.path} exact component={this.props.component} />
        }
    }
}

export default LoginRoute;