reactjs - What is the better approach to update state in redux? -


i'm new in react/redux. plese me figure out better approach update state in redux? can call bunch of actions , manage state in many cases of reducer or can manage state in react component , call 1 action update state in 1 case of reducer.

// option #1 const reducer = (state = {items: [], counter: 0, someanotherdata: {}}, action) => {     switch (action.type) {         case add_item: {             const updateditems = state.items.concat(action.payload);             return object.assign({}, state, {items: updateditems});         }         case remove_item: {             const updateditems = state.items.filter(e => e.id !== action.payload);             return object.assign({}, state, {items: updateditems});         }     }     // cases counter , someanotherdata };  // component render() {     // ...     <button onclick={() => dispatch({type: 'add_item', payload: item})}>         add     </button>     <button onclick={() => dispatch({type: 'remove_item', payload: id})}>         remove     </button>     {...} }  // option #2 const reducer = (state = {items: [], counter: 0, someanotherdata: {}}, action) => {     switch (action.type) {         case 'update_data':             return object.assign({}, state, action.payload);         // no more cases         default:             return state;     } };  // component additem = (item) => {     const updateditems = this.props.items.concat(item);     this.props.dispatch({type: 'update_data', payload: {items: updateditems}}); }  removeitem = (id) => {     const updateditems = this.props.items.filter(e => e.id !== id);     this.props.dispatch({type: 'update_data', payload: {items: updateditems}}); }  render() {     // ...     <button onclick={() => this.additem(item)}>         add     </button>     <button onclick={() => this.removeitem(id)}>     remove     </button>     {...} } 

for me option #2 seems better can see going on in same file, i'm not sure right way.

you should better use actioncreators follows:

function mapactionstoprops(dispatch) {     return {         actioncreator1: () => dispatch(updatedataac())     }; } 

pass second param while connecting component store follows:

export default connect(mapstatetoprops, mapactionstoprops)(componentname); 

then in component can make use of prop actioncreator1 invoke action creator : additemac has following definition in configuration file:

export const additemac = () => ({     type: 'add_item' }); 

that helps keep code clean , more organised.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -