【问题标题】:Having multiple API calls in one componentDidMount - possible?在一个 componentDidMount 中有多个 API 调用 - 可能吗?
【发布时间】:2020-07-15 19:05:15
【问题描述】:

我有一个相当棘手的问题。在我的 componentDidMount 方法中,我有:
1.) 在变量“dog”上设置状态 2.) 通过 axios 进行 API 调用,其响应设置另一个变量“dogName”的状态

这会产生问题(我想要呈现给浏览器的数据没有呈现) - 那么有没有更好的方法来编写我的代码?

setData = async () => {
  const x = await fetch("https://dog.ceo/api/breed/hound/images");
  const y = await x.json();
  const z = await y.message;
  
  let newArr = [];
  for (let i = 0; i < z.length; i++) {
    if (i <= 9) {
      newArr.push(z[i]);
    }
   }
  return newArr;
  };

componentDidMount() {
  this.setState({
    loading:true
  })
  this.setData()
  .then(res =>{
    this.setState({
      loading:false,
      dog: res,
    })
  })
    axios.get('http://localhost:3000/dogs')
    .then(res => {
        this.setState({
            dogName:res.data
          })
        })
        .catch(error => {
          console.log(error)
        })
      }

【问题讨论】:

    标签: reactjs http axios


    【解决方案1】:

    这应该可以解决问题

    您同时监听两个 Promise 解析,然后使用您获得的所有数据执行 setState。 我给你的建议是:你应该研究 react hooks 甚至 react-redux 来获取不直接在你的组件代码中的数据:)

    componentDidMount() {
      this.setState({
        loading: true,
      });
    
      const dogPromise = this.setData();
      const dogNamePromise = axios.get('http://localhost:3000/dogs');
    
      Promise.all([
          dogPromise,
          dogNamePromise
      ])
        .then(([dogResponse, dogNameResponse]) => {
          this.setState({
            loading: false,
            dog: dogResponse,
            dogName: dogNameResponse.data,
          });
        })
        .catch(error => {
          console.log(error);
        });
    }
    

    【讨论】:

    • 您好,感谢您的帮助!我实现了您的代码,但仍然遇到问题。有趣的是,当我刚刚调用 '/dogs' 端点时,它起作用了。当我在 componentDidMount 中进行这两个调用时,它似乎只是废话。以下是有效的方法:componentDidMount() { axios.get('http://localhost:5000/dogs') .then(res =&gt; { this.setState({ dogName:res.data }) }) }
    • 是否抛出错误?当您将console.log(this.state) 放入渲染函数时,“狗”部分是否存在?也许你可以展示你的render函数,也许那里有一个小错误:)
    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 2020-03-06
    • 2012-01-05
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    相关资源
    最近更新 更多