Guest User

Untitled

a guest
Jan 19th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import * as React from "react";
  2. import { render } from "react-dom";
  3. import { Store, createStore } from "redux";
  4. import { Provider, connect } from "react-redux";
  5.  
  6. interface AppState {
  7. count: number
  8. }
  9.  
  10. interface Type {
  11. type: string
  12. }
  13.  
  14. type Action<T> = Type & T;
  15.  
  16. const initial: AppState = {
  17. count: 0
  18. };
  19.  
  20. const reducer = (state: AppState = initial, action: Action<{}>): AppState => {
  21. switch (action.type) {
  22. case 'ADD':
  23. return { count: state.count + 1 };
  24. case 'SUB':
  25. return { count: state.count - 1 };
  26. default:
  27. return state;
  28. }
  29. };
  30.  
  31. const store: Store<AppState> = createStore(reducer);
  32.  
  33. interface StateProps {
  34. count: number
  35. }
  36.  
  37. interface DispatchProps {
  38. onAdd: <T>(event: React.MouseEvent<T>) => void
  39. onSub: <T>(event: React.MouseEvent<T>) => void
  40. }
  41.  
  42. type AppProps = StateProps & DispatchProps;
  43.  
  44. const AppRedux = (props: AppProps): JSX.Element =>
  45. <div>
  46. <button onClick={ props.onSub }>-</button>
  47. { props.count }
  48. <button onClick={ props.onAdd }>+</button>
  49. </div>
  50. ;
  51.  
  52. const mapStateToProps = (state: AppState): StateProps => ({
  53. count: state.count
  54. });
  55.  
  56. const mapDispatchToProps = (dispatch: (action: Action<{}>) => void): DispatchProps => ({
  57. onAdd<T>(event: React.MouseEvent<T>): void {
  58. dispatch({ type: 'ADD' });
  59. },
  60. onSub<T>(event: React.MouseEvent<T>): void {
  61. dispatch({ type: 'SUB' });
  62. }
  63. });
  64.  
  65. const App = connect(
  66. mapStateToProps,
  67. mapDispatchToProps
  68. )(AppRedux)
  69.  
  70. render(
  71. <Provider store={ store }>
  72. <App />
  73. </Provider>,
  74. document.querySelector('#app')
  75. );
Add Comment
Please, Sign In to add comment