reactjs - how should I build onClick action in my react component + Redux -


i've been through many tutorials , questions on stack can't find solution. i'm learning react/redux, trying build onclick action. i've got following error "maximum call stack size exceeded error". got because i'm rendering function that's changing state infinitely. i'm trying deal <button onclick={displaytable(click)}>cool</button> differently nothing seems work. know action , guess reducers works since when i'm dispatching action trough console : $r.store.dispatch({type: 'set_table_data'});, state updated properly.

any advices ?

here action :

export const settablefilter = (click) => {   return {     type: 'set_table_data',     click : click,   }; }; 

here reducer :

const tablefilter = (state = 0, action) => {     if(action.type === 'set_table_data') {         return state + 1;     }         return state;   } 

and here component :

const displaytable = (click) => {          return (         <div>             <button onclick={displaytable(click)}>cool</button>         </div> )     }   function mapstatetoprops(state) {   return {       click: state.tablefilter.click   }; };   const mapdispachtoprops = (dispatch) => {     return {   displaytable: (click) => {dispatch (settablefilter(click));         },     }; };  const apptable = connect(mapstatetoprops, mapdispachtoprops)(displaytable);  export default apptable; 

i know should build reducer in way state should updated without mutation, i'll keep later ! :)

thanks.

the answer given doesn't explain why code not working, thought i'd expand on that.

your problem exceeding function call stack, more commonly known infinite loop. reason happening because aren't passing function onclick attribute of button, rather invoking function , passing return value instead. following scenario happening:

  • react component mounted dom
  • render() called
  • the displaytable function invoked, dispatches update store
  • the store updates, , passes new props react component
  • render() called again
  • displaytable invoked again

...and on.

what you'll want instead pass function button's onclick attribute. component should this:

const component = props => {     return (         <div>             <button onclick={props.displaytable}>cool</button>         </div>     ); }; 

in above code snippet, removed click prop because doesn't you're using @ (given code posted in op).


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -