【发布时间】:2019-05-07 19:03:30
【问题描述】:
在 componentDidMount 中,我试图从 /api/topics/${params.TopicId 路由中获取名为 topic 的数据,然后从响应中我只想将 topic.user_id 发送到另一条路由并获取整个用户作为响应。但这不起作用,因为它们同时发送请求,因此 topic.user_id 的状态为空。这是一种我可以采取响应并将其提供给另一个请求的方式吗?我在 componentDidMount 中做,所以它会在组件渲染之前完成。
componentDidMount() {
const {
match: { params }
} = this.props;
axios
.get(`/api/topics/${params.TopicId}`)
.then(response => {
this.setState({ topic: response.data });
})
.catch(function(error) {
console.log(error);
});
axios
.get(`/api/users/${this.state.topic.user_id}`)
.then(response => {
this.setState({ user: response.data });
})
.catch(function(error) {
console.log(error);
});
}
【问题讨论】:
标签: javascript reactjs axios