一旦用户与您的应用进行交互,如何在componentDidMount之后使用Axios进行第二次API获取请求调用?

时间:2018-11-05 07:50:58

标签: reactjs axios

我正在使用Axios在生命周期方法componentDidMount中使API调用(获取请求)。

一切正常,我得到了结果,并使用setState保存了数据。

componentDidMount(){
   axios.get("https://myAPI/v1/myAPI-Endpoint?myAPI-Key=12345678910abcdef")
     .catch(error => console.log('Error', error))
     .then(
       (response) => {
         let data = response.data;
         this.setState({
           myFetchedData: data
         });
       },
     )
}
  • 然后,我使用获取的数据填充自动完成输入,一旦用户选择了值,我想使用所选值进行另一个API调用

问题:

  • 我现在应该在哪里进行第二个API调用,我假设由于组件已经安装,所以无法在componentDidMount中进行此操作?

  • 那么这里的最佳实践是什么?我应该在哪里执行由用户操作触发的API调用?

1 个答案:

答案 0 :(得分:1)

您的自动填充组件可能会在选择时触发某种事件(例如'onChange','onSelect'等,这取决于组件)。

然后,您可以在渲染功能中执行以下操作:

<AutoComplete
  onSelect={this.handleAutoCompleteSelect}
  …
/>

然后在组件类内部:

…
handleAutoCompleteSelect (value) {
  axios.get(apiEndpont, { value }) // Exact request depends on your api implementation
    .catch(…)
    .then(function (res) {
      // Process request result here
    })
}