React中嵌套获取请求的问题

Jou*_*anM 4 javascript api fetch reactjs

我是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 })
            })

    }
Run Code Online (Sandbox Code Playgroud)

有了这段代码,我有了要呈现表的数据,但是我需要运行另一个访存来获取其他信息,其ID来自第一个请求。

我该如何执行嵌套的提取请求?

非常感谢,

马修

zhu*_*ber 5

您可以使用以下方法轻松管理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 });
}
Run Code Online (Sandbox Code Playgroud)

您可以阅读有关异步功能的更多信息。