Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. import React from "react";
  2. import { render } from "react-dom";
  3.  
  4. import { createStore, Action, Dispatch } from "redux";
  5. import { connect, Provider } from "react-redux";
  6.  
  7. // my state
  8. interface State
  9. {
  10. number: number;
  11. }
  12.  
  13. const initialState: State = { number: 0 };
  14.  
  15. // action(s)
  16. const ADD_ACTION = "ADD"; // action type name
  17. interface AddAction extends Action
  18. {
  19. number: number;
  20. }
  21. function add(number: number): AddAction
  22. {
  23. return {
  24. type: ADD_ACTION,
  25. number: number
  26. };
  27. }
  28.  
  29. // reducer
  30. function reducer(state = initialState, action: Action): State
  31. {
  32. switch (action.type)
  33. {
  34. case ADD_ACTION:
  35. return Object.assign({}, state, { number: state.number + (action as AddAction).number }); // always copy the state, never return a reference to the previous one
  36.  
  37. default:
  38. return state;
  39. }
  40. }
  41.  
  42. // store
  43. const store = createStore(reducer, initialState);
  44.  
  45. // react
  46. interface StateProps // global type, import in every component
  47. {
  48. state: State;
  49. }
  50.  
  51. interface DispatchProps // global type, import in every component
  52. {
  53. dispatch: Dispatch<any>;
  54. }
  55.  
  56. // local component - e.g. NumberView.tsx
  57. export interface NumberViewProps
  58. {
  59. prefix: string;
  60. }
  61.  
  62. // no export there, this is a private class (could be a stateless component too)
  63. class NumberViewComponent extends React.Component<StateProps & DispatchProps & NumberViewProps, {}> // note the intersection and empty interface as the state
  64. {
  65. public render(): JSX.Element
  66. {
  67. return (
  68. <span onClick={ () => this.props.dispatch(add(1)) }>{ this.props.prefix }{ this.props.state.number }</span>
  69. );
  70. }
  71. }
  72.  
  73. // exported decorated component, this time no intersection so the props are properly set (don't contain )
  74. export const NumberView = connect<StateProps, DispatchProps, NumberViewProps>((state: State) => ({ state }))(NumberViewComponent);
  75.  
  76. // use the class!
  77. render(<Provider store={ store }><NumberView prefix={ "Number: " } /></Provider>, document.getElementById("app"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement