简体   繁体   中英

How can I setstate before making function call in react?

<li
  key={suggestion.id}
  id={`suggestion-${index}`}
  className="suggestion-list-item"
  onClick={e => this.props.checkToShare(e, suggestion)}
>

How can I add setState and then call the prop func on my onClick event?

您可以调用 setState 并使用其回调函数:

 this.setState({...}, ()=>{ /* other function */})

You can use a callback in setState that will be triggered once your state is updated:

const handleClick = evt => {
  this.setState(..., () => {
    this.props.checkToShare(evt, suggestion)
  })
}
...

<li
  key={suggestion.id}
  id={`suggestion-${index}`}
  className="suggestion-list-item"
  onClick={handleClick}
>

Just and {} for arrow function

   <li
      key={suggestion.id}
      id={`suggestion-${index}`}
      className="suggestion-list-item"
      onClick={e => {
        this.setState({ clicked: "yes" });
        this.props.checkToShare(e, suggestion);
      }}
    ></li>

Better go for another async method for a cleaner code.

<li
  key={suggestion.id}
  id={`suggestion-${index}`}
  className="suggestion-list-item"
  onClick={e => this.cleanerWay(e,suggestion)}
>

cleanerWay=async(e,suggestion)=>{
/**setting state**/
await this.setState({suggestion});
/**calling the action**/
await this.props.checkToShare(e, suggestion);
}

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