在 componentDidMount 中从一个 axios 获取数据到另一个

db1*_*b14 3 javascript reactjs axios

在 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);
      });
  }
Run Code Online (Sandbox Code Playgroud)

Nao*_*dgi 5

componentDidMount() {
  const {
    match: { params }
  } = this.props;

  fetch(`/api/topics/${params.TopicId}`,(response)=>{
    this.setState({ topic: response.data } , 
      {
        fetch(`/api/users/${this.state.topic.user_id}` ,(response)=>{
          this.setState({ user: response.data });
        } )
      });

}

const fetch = (uri,callBack) =>{
  axios
  .get(uri)
  .then(response => {
    callBack(response)
  })
  .catch(function(error) {
    console.log(error);
  });
}
Run Code Online (Sandbox Code Playgroud)

最好使用设置状态回调参数

setState(updater[, callback])
Run Code Online (Sandbox Code Playgroud)

https://reactjs.org/docs/react-component.html#setstate

因为您需要在下一次获取之前更新状态