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);
My current solution is to put extra code in render function and not to use component property.
<Route exact path="/" render={() => {
getInitialData();
return <Home />;
} } />