我正在使用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调用,我假设由于组件已经安装,所以无法在componentDidMount
中进行此操作?
那么这里的最佳实践是什么?我应该在哪里执行由用户操作触发的API调用?
答案 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
})
}