Working React+Redux template

This commit is contained in:
SteveSandersonMS
2016-03-07 14:32:36 +00:00
parent ec9337754f
commit cf7a519919
26 changed files with 1475 additions and 131 deletions

View File

@@ -1,15 +1,24 @@
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import './css/site.css';
import 'bootstrap/dist/css/bootstrap.css';
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 routes from './routes';
import configureStore from './configureStore';
import { ApplicationState } from './store';
// 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);
// 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(
<Router history={ browserHistory } children={ routes } />,
<Provider store={ store }>
<Router history={ history } children={ routes } />
</Provider>,
document.getElementById('react-app')
);

View File

@@ -1,30 +1,27 @@
import * as React from 'react';
import { Link } from 'react-router';
import { provide } from 'redux-typed';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';
interface CounterState {
currentCount: number;
}
export class Counter extends React.Component<any, CounterState> {
constructor() {
super();
this.state = { currentCount: 0 };
}
class Counter extends React.Component<CounterProps, void> {
public render() {
return <div>
<h1>Counter</h1>
<p>This is a simple example of a React component.</p>
<p>Current count: <strong>{ this.state.currentCount }</strong></p>
<p>Current count: <strong>{ this.props.count }</strong></p>
<button onClick={ () => { this.incrementCounter() } }>Increment</button>
<button onClick={ () => { this.props.increment() } }>Increment</button>
</div>;
}
incrementCounter() {
this.setState({
currentCount: this.state.currentCount + 1
});
}
}
// Build the CounterProps type, which allows the component to be strongly typed
const provider = provide(
(state: ApplicationState) => state.counter, // Select which part of global state maps to this component
CounterStore.actionCreators // Select which action creators should be exposed to this component
);
type CounterProps = typeof provider.allProps;
export default provider.connect(Counter);

View File

@@ -1,36 +1,36 @@
import * as React from 'react';
import { Link } from 'react-router';
import { provide } from 'redux-typed';
import { ApplicationState } from '../store';
import * as WeatherForecastsState from '../store/WeatherForecasts';
interface FetchDataExampleState {
forecasts: WeatherForecast[];
loading: boolean;
interface RouteParams {
startDateIndex: string;
}
export class FetchData extends React.Component<any, FetchDataExampleState> {
constructor() {
super();
this.state = { forecasts: [], loading: true };
fetch('/api/SampleData/WeatherForecasts')
.then(response => response.json())
.then((data: WeatherForecast[]) => {
this.setState({ forecasts: data, loading: false });
});
class FetchData extends React.Component<WeatherForecastProps, void> {
componentWillMount() {
// This method runs when the component is first added to the page
let startDateIndex = parseInt(this.props.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;
this.props.requestWeatherForecasts(startDateIndex);
}
public render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: FetchData.renderForecastsTable(this.state.forecasts);
return <div>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
{ contents }
<p>For more sophisticated applications, consider an architecture such as Redux or Flux for managing state. You can generate an ASP.NET Core application with React and Redux using <code>dotnet new aspnet/spa/reactredux</code> instead of using this template.</p>
<p>This component demonstrates fetching data from the server and working with URL parameters.</p>
{ this.renderForecastsTable() }
{ this.renderPagination() }
</div>;
}
private static renderForecastsTable(forecasts: WeatherForecast[]) {
private renderForecastsTable() {
return <table className='table'>
<thead>
<tr>
@@ -41,7 +41,7 @@ export class FetchData extends React.Component<any, FetchDataExampleState> {
</tr>
</thead>
<tbody>
{forecasts.map(forecast =>
{this.props.forecasts.map(forecast =>
<tr key={ forecast.dateFormatted }>
<td>{ forecast.dateFormatted }</td>
<td>{ forecast.temperatureC }</td>
@@ -52,11 +52,23 @@ export class FetchData extends React.Component<any, FetchDataExampleState> {
</tbody>
</table>;
}
private renderPagination() {
let prevStartDateIndex = this.props.startDateIndex - 5;
let nextStartDateIndex = this.props.startDateIndex + 5;
return <p className='clearfix text-center'>
<Link className='btn btn-default pull-left' to={ `/fetchdata/${ prevStartDateIndex }` }>Previous</Link>
<Link className='btn btn-default pull-right' to={ `/fetchdata/${ nextStartDateIndex }` }>Next</Link>
{ this.props.isLoading ? <span>Loading...</span> : [] }
</p>;
}
}
interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
// Build the WeatherForecastProps type, which allows the component to be strongly typed
const provider = provide(
(state: ApplicationState) => state.weatherForecasts, // Select which part of global state maps to this component
WeatherForecastsState.actionCreators // Select which action creators should be exposed to this component
).withExternalProps<{ params: RouteParams }>(); // Also include a 'params' property on WeatherForecastProps
type WeatherForecastProps = typeof provider.allProps;
export default provider.connect(FetchData);

View File

@@ -1,13 +1,13 @@
import * as React from 'react';
export class Home extends React.Component<any, void> {
export default class Home extends React.Component<any, void> {
public render() {
return <div>
<h1>Hello, world!</h1>
<p>Welcome to your new single-page application, built with:</p>
<ul>
<li><a href='https://get.asp.net/'>ASP.NET Core</a> and <a href='https://msdn.microsoft.com/en-us/library/67ef8sbd.aspx'>C#</a> for cross-platform server-side code</li>
<li><a href='https://facebook.github.io/react/'>React</a> and <a href='http://www.typescriptlang.org/'>TypeScript</a> for client-side code</li>
<li><a href='https://facebook.github.io/react/'>React</a>, <a href='http://redux.js.org'>Redux</a>, and <a href='http://www.typescriptlang.org/'>TypeScript</a> for client-side code</li>
<li><a href='https://webpack.github.io/'>Webpack</a> for building and bundling client-side resources</li>
<li><a href='http://getbootstrap.com/'>Bootstrap</a> for layout and styling</li>
</ul>
@@ -18,11 +18,6 @@ export class Home extends React.Component<any, void> {
<li><strong>Hot module replacement</strong>. In development mode, you don't even need to reload the page after making most changes. Within seconds of saving changes to files, rebuilt CSS and React components will be injected directly into your running application, preserving its live state.</li>
<li><strong>Efficient production builds</strong>. In production mode, development-time features are disabled, and the <code>webpack</code> build tool produces minified static CSS and JavaScript files.</li>
</ul>
<h4>Going further</h4>
<p>
For larger applications, or for server-side prerendering (i.e., for <em>isomorphic</em> or <em>universal</em> applications), you should consider using a Flux/Redux-like architecture.
You can generate an ASP.NET Core application with React and Redux using <code>dotnet new aspnet/spa/reactredux</code> instead of using this template.
</p>
</div>;
}
}

View File

@@ -0,0 +1,33 @@
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import * as thunkModule from 'redux-thunk';
import { routerReducer } from 'react-router-redux';
import * as Store from './store';
import { typedToPlain } from 'redux-typed';
export default function configureStore(initialState?: Store.ApplicationState) {
// Build middleware. These are functions that can process the actions before they reach the store.
const thunk = (thunkModule as any).default; // Workaround for TypeScript not importing thunk module as expected
const devToolsExtension = (window as any).devToolsExtension; // If devTools is installed, connect to it
const createStoreWithMiddleware = compose(
applyMiddleware(thunk, typedToPlain),
devToolsExtension ? devToolsExtension() : f => f
)(createStore);
// Combine all reducers and instantiate the app-wide store instance
const allReducers = buildRootReducer(Store.reducers);
const store = createStoreWithMiddleware(allReducers, initialState) as Redux.Store;
// Enable Webpack hot module replacement for reducers
if (module.hot) {
module.hot.accept('./store', () => {
const nextRootReducer = require<typeof Store>('./store');
store.replaceReducer(buildRootReducer(nextRootReducer.reducers));
});
}
return store;
}
function buildRootReducer(allReducers) {
return combineReducers(Object.assign({}, allReducers, { routing: routerReducer })) as Redux.Reducer;
}

View File

@@ -1,12 +1,14 @@
import * as React from 'react';
import { Router, Route, HistoryBase } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
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='/fetchdata' components={{ body: FetchData }}>
<Route path='(:startDateIndex)' /> { /* Optional route segment that does not affect NavMenu highlighting */ }
</Route>
</Route>;

View File

@@ -0,0 +1,40 @@
import { typeName, isActionType, Action, Reducer } from 'redux-typed';
import { ActionCreator } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface CounterState {
count: number;
}
// -----------------
// ACTIONS - These are serializable (hence replayable) descriptions of state transitions.
// They do not themselves have any side-effects; they just describe something that is going to happen.
// Use @typeName and isActionType for type detection that works even after serialization/deserialization.
@typeName("INCREMENT_COUNT")
class IncrementCount extends Action {
}
// ----------------
// ACTION CREATORS - These are functions exposed to UI components that will trigger a state transition.
// They don't directly mutate state, but they can have external side-effects (such as loading data).
export const actionCreators = {
increment: (): ActionCreator => (dispatch, getState) => {
dispatch(new IncrementCount());
}
};
// ----------------
// REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.
export const reducer: Reducer<CounterState> = (state, action) => {
if (isActionType(action, IncrementCount)) {
return { count: state.count + 1 };
}
// For unrecognized actions (or in cases where actions have no effect), must return the existing state
// (or default initial state if none was supplied)
return state || { count: 0 };
};

View File

@@ -0,0 +1,76 @@
import { fetch } from 'domain-task/fetch';
import { typeName, isActionType, Action, Reducer } from 'redux-typed';
import { ActionCreator } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface WeatherForecastsState {
isLoading: boolean;
startDateIndex: number;
forecasts: WeatherForecast[];
}
export interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
// -----------------
// ACTIONS - These are serializable (hence replayable) descriptions of state transitions.
// They do not themselves have any side-effects; they just describe something that is going to happen.
// Use @typeName and isActionType for type detection that works even after serialization/deserialization.
@typeName("REQUEST_WEATHER_FORECASTS")
class RequestWeatherForecasts extends Action {
constructor(public startDateIndex: number) {
super();
}
}
@typeName("RECEIVE_WEATHER_FORECASTS")
class ReceiveWeatherForecasts extends Action {
constructor(public startDateIndex: number, public forecasts: WeatherForecast[]) {
super();
}
}
// ----------------
// ACTION CREATORS - These are functions exposed to UI components that will trigger a state transition.
// They don't directly mutate state, but they can have external side-effects (such as loading data).
export const actionCreators = {
requestWeatherForecasts: (startDateIndex: number): ActionCreator => (dispatch, getState) => {
// Only load data if it's something we don't already have (and are not already loading)
if (startDateIndex !== getState().weatherForecasts.startDateIndex) {
fetch(`/api/SampleData/WeatherForecasts?startDateIndex=${ startDateIndex }`)
.then(response => response.json())
.then((data: WeatherForecast[]) => {
dispatch(new ReceiveWeatherForecasts(startDateIndex, data));
});
dispatch(new RequestWeatherForecasts(startDateIndex));
}
}
};
// ----------------
// REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.
const unloadedState: WeatherForecastsState = { startDateIndex: null, forecasts: [], isLoading: false };
export const reducer: Reducer<WeatherForecastsState> = (state, action) => {
if (isActionType(action, RequestWeatherForecasts)) {
return { startDateIndex: action.startDateIndex, isLoading: true, forecasts: state.forecasts };
} else if (isActionType(action, ReceiveWeatherForecasts)) {
// Only accept the incoming data if it matches the most recent request. This ensures we correctly
// handle out-of-order responses.
if (action.startDateIndex === state.startDateIndex) {
return { startDateIndex: action.startDateIndex, forecasts: action.forecasts, isLoading: false };
}
}
// For unrecognized actions (or in cases where actions have no effect), must return the existing state
// (or default initial state if none was supplied)
return state || unloadedState;
};

View File

@@ -0,0 +1,21 @@
import { ActionCreatorGeneric } from 'redux-typed';
import * as WeatherForecasts from './WeatherForecasts';
import * as Counter from './Counter';
// The top-level state object
export interface ApplicationState {
counter: Counter.CounterState,
weatherForecasts: WeatherForecasts.WeatherForecastsState
}
// Whenever an action is dispatched, Redux will update each top-level application state property using
// the reducer with the matching name. It's important that the names match exactly, and that the reducer
// acts on the corresponding ApplicationState property type.
export const reducers = {
counter: Counter.reducer,
weatherForecasts: WeatherForecasts.reducer
};
// This type can be used as a hint on action creators so that its 'dispatch' and 'getState' params are
// correctly typed to match your store.
export type ActionCreator = ActionCreatorGeneric<ApplicationState>;