如何在同一页面的React-native中从多个api端点获取数据

时间:2020-02-19 21:32:33

标签: react-native fetch datasource

我正在尝试从两个不同的api端点获取数据,并试图在我的React本机应用程序的This is the snapshot of the error I'm getting with the code snippet

中在同一页面中显示整个数据。

1 个答案:

答案 0 :(得分:1)

我也遇到了同样的例外...尝试了一种不同的方法,将一种获取方法绑定到另一种获取方法中,并尝试将值设置为第一个获取块中的所有数据源变量,然后在再次获取下一个块。

问题已解决,现在可以根据需要提供值。不知道这是否是完美的方法,但是它解决了问题,请尝试参考以下示例

fetch(‘endpoint1’, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            //send the parameters you need to use to fetch the data 
 from endpoint
    //e.g.  “id”: this.state.id,
    …   
        })
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                dataSource1: responseJson,
                dataSource2: responseJson,
            })

        })
        .then(()=>{
        fetch(‘endpoint2', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            //send the parameters you need to use to fetch the data 
from endpoint
    //e.g.  “id”: this.state.id,
    …   
        })
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                dataSource2: responseJson,
            })
        })
        })
        .catch((error) => {
            console.error(error);
        });