How should you React to Redux
What's redux?
Redux State container Implements Flux
Unidirectional
Actions actions don't do anything only contain information have no idea how to update a store
Actions function addTodo(task) { return { type: 'ADD_TODO', payload: task, }; }
Actions - test describe('TodoAction creator', () => { it('should create ADD_TODO action', () => { const expectedAction = { type: 'ADD_TODO', payload: 'test', }; expect(todoAction('test')).to.be.deep.equal(expectedAction); }); });
Dispatcher can register stores (listeners) sends actions to all stores (listeners) have no idea how to update a store
Store listens for actions creates new state from old state and action knows how to update a store
Store - reducer function todoReducer(state = initialState, action) { switch (action.type) { case 'ADD_TODO': return { ...state, list: [ ...state.list, action.payload, ], }; default: return state; } }
Reducer - test describe('todoReducer', () => { it('should return initial state', () => { expect(todoReducer(undefined, {})).to.be.deep.equal(initialState); }); it('should add element to list', () => { const name = 'testName'; const action = { type: 'ADD_TODO', payload: name, }; const expectedState = { list: [ name, ], }; expect(todoReducer(initialState, action)).to.be.deep.equal(expectedState); }); });
View represents current state can should listen for store updates have no idea how to update a store
class TodoList extends Component { static propTypes = { list: PropTypes.array, }; render() { const { list } = this.props; return (<div> <ul> {list.map(element => <li key={key}>{element}</li>)} </ul> </div> ); } } export default connect( state => ({ list: state.todo.list, }) )(TodoList);
How to update the state? view can send action to dispatcher have no idea how to update a store does not have to know what happens next only what it wants to achieve
class TodoList extends Component { static propTypes = { list: PropTypes.array, addItem: PropTypes.func, }; render() { const { list } = this.props; return (<div> <button onClick={() => this.props.addItem('New item')}/> <ul> {list.map(element => <li key="{key}">{element}</li>)} </ul> </div> ); } } export default connect( state => ({ list: state.todo.list, }), { addItem, } )(TodoList);
Let's code!
Thank you!

How should you React to Redux