在React,componentDidUpdate或eventHandler中对事件进行API调用? [英] API call on event in react, componentDidUpdate or eventHandler?

查看:109
本文介绍了在React,componentDidUpdate或eventHandler中对事件进行API调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理想情况下,我们应该在React发生事件的地方放置一个api调用

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

eventHandler componentDidUpdate 内部?

示例:

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);
  }
}

推荐答案

我没有看到等待组件更新的任何理由,我只是将其放在事件处理程序中.

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

自然地,无论哪种情况,您的组件都需要知道如何在具有选定项但还没有来自API的数据时适当地呈现...

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...

(旁注:如果 requestDataActionDispatch 导致组件状态发生变化,则在请求之前设置所选项目时,您可能希望清除该状态,因此您没有选择任何一项,但仍具有与上一项有关的状态.但是我从事实发现,它位于 props 上,它没有...)

(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...)

这篇关于在React,componentDidUpdate或eventHandler中对事件进行API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆