简体   繁体   中英

Dispatch action for onClick event

In react component I have made a function as

 handleClick(event, key, value) {
    event.preventDefault()
    this.setState({
      query:"",
      key:key,
      value:value
    });
    this.props.onClick(this.state);
    console.log("key...." + key   );
    console.log("val...." + value);
  }

this should be called when I am clicking a link

onClick={(e) => this.handleClick(e, {key}, {el}) }

Also using connect I am dispatching action as follows

export const mapDispatchToProps = (dispatch) => ({

  onClick: (query, key, value) => dispatch(onSearch(query,key, value)


  )
});

But on search method key and value are coming as undefined.But in handleClick function I am getting

key....[object Object]
val....[object Object]

key and value will be undefined. You need to call props method on callback of setState because you will not get updated state value just after calling setState.

handleClick(event, key, value) {
        event.preventDefault()
        this.setState({
          query:"",
          key:key,
          value:value
        },()=>{

           this.props.onClick(this.state);
        console.log("key...." + key   );
        console.log("val...." + value);
    });

      }

The way your calling the 'onClick' function is wrong, right now you are only passing one argument and not three.

It should be called like this

this.props.onClick(query, key, value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM