how should you react to redux

Post on 13-Apr-2017

2.584 Views

Category:

Software

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

How should youReact to Redux

What's redux?

Redux

State containerImplements Flux

Unidirectional

Actions

actions don't do anythingonly contain informationhave no idea how to update a store

Actionsfunction addTodo(task) { return { type: 'ADD_TODO', payload: task, }; }

Actions - testdescribe('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 actionscreates new state from old state and actionknows how to update a store

Store - reducerfunction todoReducer(state = initialState, action) { switch (action.type) { case 'ADD_TODO': return { ...state, list: [ ...state.list, action.payload, ], }; default: return state; } }

Reducer - testdescribe('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 statecan should listen for store updateshave 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 dispatcherhave no idea how to update a storedoes not have to know what happens nextonly 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!

top related