【问题标题】:Problem with nested fetch request in ReactReact 中嵌套获取请求的问题
【发布时间】:2020-01-17 01:03:40
【问题描述】:

React 新手,我目前正在尝试使用来自 API 的数据创建一个数据表。 我想进行第一次提取,然后使用第一个 (id) 的响应运行另一个以完成我的表格。

这是我的代码:

class HomePage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            user: {},
            data: []
        };
    }

    componentDidMount() {
        this.setState({
            user: JSON.parse(localStorage.getItem('user'))
        }, function () {
            this.loadAllObjectsInfo()
        });
    }

    // Fetch all object info in order to fill the table
    loadAllObjectsInfo() {
        const requestOptions = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'bbuser': this.state.user.userId,
                'bbtoken': this.state.user.secret
            },
        };

        fetch('https://xxxxx/api/objects', requestOptions)
            .then(response => response.json())
            .then((data) => {
                this.setState({ data: data })
            })

    }

有了这段代码,我有了想要呈现表格的数据,但我需要运行另一个 fetch 来获取其他信息,其中 id 来自第一个请求。

如何执行嵌套的获取请求?

非常感谢,

马修

【问题讨论】:

  • async/await 是一个不错的选择,而不是写承诺。 Promise 会带你去回调地狱。

标签: javascript reactjs api fetch


【解决方案1】:

您可以使用async/await 轻松管理:

async loadAllObjectsInfo() {
    const requestOptions = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'bbuser': this.state.user.user
            'bbtoken': this.state.user.secret
        },
    };

    let response = await fetch('https://xxxxx/api/objects', requestOptions);
    let data = await response.json();

    // here is another fetch - change to fit your request parameters (this is just example)
    let info = await fetch('https://xxxxx/api/objects/' + data.id);

    this.setState({ data });
}

你可以阅读更多关于async function的信息。

【讨论】:

    【解决方案2】:

    @JourdanM,您应该从then 处理程序之一返回一个新的fetch 请求。我为你做了一个简单的sn-p。没有数据验证器和微调器。这是一个简单的展示。 =)

    fetch 请求返回一个 Promise,您可以通过简单地从 then 处理程序返回它们来链接 Promise。这是一篇关于它的好文章,它有很好的例子:https://javascript.info/promise-chaining

    function fetchUser (user) {
      return fetch(`https://api.github.com/users/${user.login}`)
    }
    
    class User extends React.Component {
      state = {
        user: null
      }
    
      componentDidMount () {
        fetch("https://api.github.com/users")
          .then(response => response.json())
          .then(users => fetchUser(users[0]))
          .then(response => response.json())
          .then(user => {
            this.setState({user})
          })
      }
      
      render () {
        return (
          <div>
            <pre>{JSON.stringify(this.state.user, null, 2)}</pre>
          </div>
        )
      }
    }
    
    ReactDOM.render(<User />, document.querySelector("#root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

      【解决方案3】:

      您可以编写如下代码。

      fetch('https://xxxxx/api/objects', requestOptions)
      .then(response => response.json())
      .then((res1) => {
      
          fetch('https://xxxxx/api/objects', requestOptions)
          .then(response => response.json())
          .then((res2) => {
              this.setState({ data: res2 });
          });
      
      });
      

      希望这对你有用!

      【讨论】:

        【解决方案4】:

        你也可以像下面这样使用 axios

        axios.post(url, data, header).then(res => {
                if(res.status === 200){
                     console.log('1st data')
                    axios.post(url, data, header)
                        .then(response => {
                            if (response.status === 200) {
                                console.log('2nd data')
                            } else {
                                console.log('2nd error')
                            }
                        });
        
                }else{
                    console.log('1st error')
                }
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多