Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Redux
- ```jsx
- // Action type.
- const ADD_TODO = 'ADD_TODO';
- // Action creator.
- function addTodo(todo) {
- return { type: ADD_TODO, todo };
- }
- // Reducer state.
- initialState = {
- todos: ['Buy coffee'],
- };
- // Reducer.
- function todoReducer(state = initialState, action) {
- switch (action.type) {
- // Handle each possible type of action.
- case ADD_TODO:
- return {
- ...state,
- todos: todos.concat(action.todo),
- },
- default:
- return state;
- }
- }
- // Create a store from your reducer.
- const todoStore = createStore(todoReducer);
- // Invoke an action.
- todoStore.dispatch(addTodo('Drink coffee'));
- // Render a component.
- const TodoSummary = (props) => {
- const { todos } = props;
- return (
- <div>{todos.length}</div>
- );
- }
- // Extract props for your component.
- function mapStateToProps(todoStore, props) {
- return {
- todos: todoStore.todos,
- };
- }
- // Connect your component to the store.
- const TodoSummaryConnected = connect(mapStateToProps)(TodoSummary);
- // Render your app.
- const App = () => (
- <Provider store={todoStore}>
- <TodoSummaryConnected />
- </Provider>
- )
- ```
- ## MobX
- ```jsx
- // Model your data and interactions.
- class TodoModel {
- @observable
- todos = ['Buy coffee'];
- @action
- addTodo(todo) {
- // Directly update the state.
- todos.push(todo);
- }
- }
- // Instantiate your model.
- const todoStore = new TodoModel();
- // Perform an action.
- todoStore.addTodo('Drink coffee');
- // Connect your component to the store and render a component.
- @inject('todoStore')
- @observer
- const TodoSummary = (props) => {
- const { todoStore: { todos } } = props;
- return (
- <div>{todos.length}</div>
- );
- }
- // Render your app.
- const App = () => (
- <Provider todoStore={todoStore}>
- <TodoSummary />
- </Provider>
- )
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement