Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. ## Redux
  2.  
  3. ```jsx
  4. // Action type.
  5. const ADD_TODO = 'ADD_TODO';
  6.  
  7. // Action creator.
  8. function addTodo(todo) {
  9. return { type: ADD_TODO, todo };
  10. }
  11.  
  12. // Reducer state.
  13. initialState = {
  14. todos: ['Buy coffee'],
  15. };
  16.  
  17. // Reducer.
  18. function todoReducer(state = initialState, action) {
  19. switch (action.type) {
  20. // Handle each possible type of action.
  21. case ADD_TODO:
  22. return {
  23. ...state,
  24. todos: todos.concat(action.todo),
  25. },
  26.  
  27. default:
  28. return state;
  29. }
  30. }
  31.  
  32. // Create a store from your reducer.
  33. const todoStore = createStore(todoReducer);
  34.  
  35. // Invoke an action.
  36. todoStore.dispatch(addTodo('Drink coffee'));
  37.  
  38. // Render a component.
  39. const TodoSummary = (props) => {
  40. const { todos } = props;
  41. return (
  42. <div>{todos.length}</div>
  43. );
  44. }
  45.  
  46. // Extract props for your component.
  47. function mapStateToProps(todoStore, props) {
  48. return {
  49. todos: todoStore.todos,
  50. };
  51. }
  52.  
  53. // Connect your component to the store.
  54. const TodoSummaryConnected = connect(mapStateToProps)(TodoSummary);
  55.  
  56. // Render your app.
  57. const App = () => (
  58. <Provider store={todoStore}>
  59. <TodoSummaryConnected />
  60. </Provider>
  61. )
  62. ```
  63.  
  64. ## MobX
  65.  
  66. ```jsx
  67. // Model your data and interactions.
  68. class TodoModel {
  69. @observable
  70. todos = ['Buy coffee'];
  71.  
  72. @action
  73. addTodo(todo) {
  74. // Directly update the state.
  75. todos.push(todo);
  76. }
  77. }
  78.  
  79. // Instantiate your model.
  80. const todoStore = new TodoModel();
  81.  
  82. // Perform an action.
  83. todoStore.addTodo('Drink coffee');
  84.  
  85. // Connect your component to the store and render a component.
  86. @inject('todoStore')
  87. @observer
  88. const TodoSummary = (props) => {
  89. const { todoStore: { todos } } = props;
  90. return (
  91. <div>{todos.length}</div>
  92. );
  93. }
  94.  
  95. // Render your app.
  96. const App = () => (
  97. <Provider todoStore={todoStore}>
  98. <TodoSummary />
  99. </Provider>
  100. )
  101. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement