Implemented react-router v4 to ReactRedux template

This commit is contained in:
Keven van Zuijlen
2017-04-12 21:28:23 +02:00
committed by Steve Sanderson
parent c791ceee49
commit 785e7d48a2
9 changed files with 67 additions and 69 deletions

View File

@@ -2,23 +2,25 @@ import './css/site.css';
import 'bootstrap';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { browserHistory, Router } from 'react-router';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
import routes from './routes';
import configureStore from './configureStore';
import { ApplicationState } from './store';
// Create browser history to use in the Redux store
const history = createBrowserHistory();
// Get the application-wide store instance, prepopulating with state from the server where available.
const initialState = (window as any).initialReduxState as ApplicationState;
const store = configureStore(initialState);
const history = syncHistoryWithStore(browserHistory, store);
const store = configureStore(history, initialState);
// This code starts up the React app when it runs in a browser. It sets up the routing configuration
// and injects the app into a DOM element.
ReactDOM.render(
<Provider store={ store }>
<Router history={ history } children={ routes } />
<ConnectedRouter history={ history } children={ routes } />
</Provider>,
document.getElementById('react-app')
);

View File

@@ -1,50 +1,46 @@
import * as React from 'react';
import { Provider } from 'react-redux';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import createMemoryHistory from 'history/lib/createMemoryHistory';
import { StaticRouter } from 'react-router-dom';
import { replace } from "react-router-redux";
import { createMemoryHistory } from 'history';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import routes from './routes';
import configureStore from './configureStore';
export default createServerRenderer(params => {
return new Promise<RenderResult>((resolve, reject) => {
// Match the incoming request against the list of client-side routes
const store = configureStore();
match({ routes, location: params.location }, (error, redirectLocation, renderProps: any) => {
if (error) {
throw error;
}
// Create memory history to use in the Redux store
const history = createMemoryHistory();
const store = configureStore(history);
// If there's a redirection, just send this information back to the host application
if (redirectLocation) {
resolve({ redirectUrl: redirectLocation.pathname });
return;
}
// Dispatch the current location so that the router knows where to go
store.dispatch(replace(params.location));
// If it didn't match any route, renderProps will be undefined
if (!renderProps) {
throw new Error(`The location '${ params.url }' doesn't match any route configured in react-router.`);
}
const context : any = {};
// Build an instance of the application
const app = (
<Provider store={ store }>
<RouterContext {...renderProps} />
</Provider>
);
const app = (
<Provider store={ store }>
<StaticRouter context={ context } location={ params.location.path } children={ routes } />
</Provider>
);
// Perform an initial render that will cause any async tasks (e.g., data access) to begin
renderToString(app);
// Perform an initial render that will cause any async tasks (e.g., data access) to begin
renderToString(app);
// Once the tasks are done, we can perform the final render
// We also send the redux store state, so the client can continue execution where the server left off
params.domainTasks.then(() => {
resolve({
html: renderToString(app),
globals: { initialReduxState: store.getState() }
});
}, reject); // Also propagate any errors back into the host application
});
// If there's a redirection, just send this information back to the host application (Maybe improve this?)
if (context.url) {
resolve({ redirectUrl: context.url });
return;
}
// Once the tasks are done, we can perform the final render
// We also send the redux store state, so the client can continue execution where the server left off
params.domainTasks.then(() => {
resolve({
html: renderToString(app),
globals: { initialReduxState: store.getState() }
});
}, reject); // Also propagate any errors back into the host application
});
});

View File

@@ -1,5 +1,5 @@
import * as React from 'react';
import { Link } from 'react-router';
import { Link, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';
@@ -22,7 +22,7 @@ class Counter extends React.Component<CounterProps, {}> {
}
// Wire up the React component to the Redux store
export default connect(
export default connect<CounterStore.CounterState, {}, RouteComponentProps<{}>>(
(state: ApplicationState) => state.counter, // Selects which state properties are merged into the component's props
CounterStore.actionCreators // Selects which action creators are merged into the component's props
)(Counter);

View File

@@ -1,25 +1,25 @@
import * as React from 'react';
import { Link } from 'react-router';
import { Link, RouteComponentProps } from 'react-router-dom';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as WeatherForecastsState from '../store/WeatherForecasts';
// At runtime, Redux will merge together...
type WeatherForecastProps =
WeatherForecastsState.WeatherForecastsState // ... state we've requested from the Redux store
& typeof WeatherForecastsState.actionCreators // ... plus action creators we've requested
& { params: { startDateIndex: string } }; // ... plus incoming routing parameters
WeatherForecastsState.WeatherForecastsState // ... state we've requested from the Redux store
& typeof WeatherForecastsState.actionCreators // ... plus action creators we've requested
& RouteComponentProps<{ startDateIndex: string }>; // ... plus incoming routing parameters
class FetchData extends React.Component<WeatherForecastProps, {}> {
componentWillMount() {
// This method runs when the component is first added to the page
let startDateIndex = parseInt(this.props.params.startDateIndex) || 0;
let startDateIndex = parseInt(this.props.match.params.startDateIndex) || 0;
this.props.requestWeatherForecasts(startDateIndex);
}
componentWillReceiveProps(nextProps: WeatherForecastProps) {
// This method runs when incoming props (e.g., route params) change
let startDateIndex = parseInt(nextProps.params.startDateIndex) || 0;
let startDateIndex = parseInt(nextProps.match.params.startDateIndex) || 0;
this.props.requestWeatherForecasts(startDateIndex);
}
@@ -67,7 +67,7 @@ class FetchData extends React.Component<WeatherForecastProps, {}> {
}
}
export default connect(
export default connect<WeatherForecastsState.WeatherForecastsState, {}, WeatherForecastProps>(
(state: ApplicationState) => state.weatherForecasts, // Selects which state properties are merged into the component's props
WeatherForecastsState.actionCreators // Selects which action creators are merged into the component's props
)(FetchData);

View File

@@ -2,7 +2,7 @@ import * as React from 'react';
import { NavMenu } from './NavMenu';
export interface LayoutProps {
body: React.ReactElement<any>;
children?: React.ReactElement<any>;
}
export class Layout extends React.Component<LayoutProps, {}> {
@@ -13,7 +13,7 @@ export class Layout extends React.Component<LayoutProps, {}> {
<NavMenu />
</div>
<div className='col-sm-9'>
{ this.props.body }
{ this.props.children }
</div>
</div>
</div>;

View File

@@ -1,5 +1,5 @@
import * as React from 'react';
import { Link } from 'react-router';
import { NavLink, Link } from 'react-router-dom';
export class NavMenu extends React.Component<{}, {}> {
public render() {
@@ -18,19 +18,19 @@ export class NavMenu extends React.Component<{}, {}> {
<div className='navbar-collapse collapse'>
<ul className='nav navbar-nav'>
<li>
<Link to={ '/' } activeClassName='active'>
<NavLink exact to={ '/' } activeClassName='active'>
<span className='glyphicon glyphicon-home'></span> Home
</Link>
</NavLink>
</li>
<li>
<Link to={ '/counter' } activeClassName='active'>
<NavLink to={ '/counter' } activeClassName='active'>
<span className='glyphicon glyphicon-education'></span> Counter
</Link>
</NavLink>
</li>
<li>
<Link to={ '/fetchdata' } activeClassName='active'>
<NavLink to={ '/fetchdata' } activeClassName='active'>
<span className='glyphicon glyphicon-th-list'></span> Fetch data
</Link>
</NavLink>
</li>
</ul>
</div>

View File

@@ -1,15 +1,17 @@
import { createStore, applyMiddleware, compose, combineReducers, GenericStoreEnhancer } from 'redux';
import thunk from 'redux-thunk';
import { routerReducer } from 'react-router-redux';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import * as Store from './store';
import { History } from 'history';
export default function configureStore(initialState?: Store.ApplicationState) {
export default function configureStore(history: History, initialState?: Store.ApplicationState) {
// Build middleware. These are functions that can process the actions before they reach the store.
const windowIfDefined = typeof window === 'undefined' ? null : window as any;
// If devTools is installed, connect to it
const devToolsExtension = windowIfDefined && windowIfDefined.devToolsExtension as () => GenericStoreEnhancer;
const middlewares = [thunk, routerMiddleware(history)];
const createStoreWithMiddleware = compose(
applyMiddleware(thunk),
applyMiddleware(...middlewares),
devToolsExtension ? devToolsExtension() : f => f
)(createStore);

View File

@@ -1,17 +1,15 @@
import * as React from 'react';
import { Router, Route, HistoryBase } from 'react-router';
import { Route } from 'react-router-dom';
import { Layout } from './components/Layout';
import Home from './components/Home';
import FetchData from './components/FetchData';
import Counter from './components/Counter';
export default <Route component={ Layout }>
<Route path='/' components={{ body: Home }} />
<Route path='/counter' components={{ body: Counter }} />
<Route path='/fetchdata' components={{ body: FetchData }}>
<Route path='(:startDateIndex)' /> { /* Optional route segment that does not affect NavMenu highlighting */ }
</Route>
</Route>;
export default <Layout>
<Route exact path='/' component={ Home } />
<Route path='/counter' component={ Counter } />
<Route path='/fetchdata/:startDateIndex?' component={ FetchData } />
</Layout>;
// Enable Hot Module Replacement (HMR)
if (module.hot) {

View File

@@ -6,7 +6,7 @@
"@types/react": "^0.14.29",
"@types/react-dom": "^0.14.14",
"@types/react-redux": "^4.4.29",
"@types/react-router": "^4.0.4",
"@types/react-router-dom": "^4.0.3",
"@types/react-router-redux": "^5.0.0",
"@types/redux": "3.5.27",
"@types/webpack": "^2.2.0",