API call on event in react, componentDidUpdate or eventHandler?

℡╲_俬逩灬. 提交于 2021-01-28 05:29:36

问题


Where should we ideally place an api call to be made on occurrence of an event in React

Inside the eventHandler or componentDidUpdate ?

example:

handleItemClick = (item) => (event) => {
  this.setState({selectedItem: item});
  this.props.requestDataActionDispatch(item);
}

OR

componentDidUpdate(prevProps, prevState, snapshot) {
  if(prevState.item !== this.state.item) {
    this.props.requestDataActionDispatch(item);
  }
}

回答1:


Depends

But a simple solution is, if you want to call some API after change of state value then you must go for eventHandler. Also check for callback in setState.

handleItemClick = (item) => (event) => {
  this.setState({selectedItem: item}, () => this.props.requestData(item));
}



回答2:


I don't see any reason to wait for component update, I'd just put it in the event handler.

Naturally, in either case your component needs to know how to render appropriately when it has a selected item but doesn't have the data from the API yet...


(Side note: If requestDataActionDispatch results in a state change in your component, you probably want to clear that state when setting the selected item prior to the request, so you don't have one item selected but still have the state related to the previous item. But I'm guessing from the fact it's on props that it doesn't...)




回答3:


It depends

I would prefer to call the api inside componentDidUpdate. Why ? Because it's cleaner. Whenever there is a change in state or props, componentDidUpdate will be called. So definitely, there has to be a condition inside componentDidUpdate like you have mentioned

if(prevState.item !== this.state.item)


来源:https://stackoverflow.com/questions/56769875/api-call-on-event-in-react-componentdidupdate-or-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!