簡體   English   中英

在componentDidMount中從一個axios到另一個axios獲取數據

[英]Getting data from one axios to another in componentDidMount

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

最好使用set state回調參數

setState(updater[, callback])

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

因為您需要在下一次提取之前更新狀態

您可以像下面這樣將您的Promises在一起:

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

  axios
    .get(`/api/topics/${params.TopicId}`)
    .then(response => {
      this.setState({ topic: response.data });
      return axios.get(`/api/users/${response.data.user_id}`);
    })
    .then(response => {
      this.setState({ user: response.data });
    })
    .catch(function(error) {
      console.log(error);
    });
}

您可以使用回調。

const func = (id, cb) => axios
  .get(`/api/topics/${id}`)
  .then(response => {
    this.setState({ topic: response.data });
    cb(response.data.user_id);
  })
  .catch(function(error) {
    console.log(error);
  });

這樣,您可以致電...

func(params.TopicId, user_id => axios
  .get(`/api/users/${user_id}`)
  .then(response => {
    this.setState({ user: response.data });
  })
  .catch(function(error) {
    console.log(error);
  })
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM