1. 程式人生 > >React Native ---fetch 之GET請求帶引數

React Native ---fetch 之GET請求帶引數

網上關於其GET請求的用例全是沒有帶引數的,帶引數的又全部是POST請求下面給出帶引數的做法.

export function  get(url,params){
        if (params) {
            let paramsArray = [];
            //拼接引數
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
        //fetch請求
        fetch(url,{
            method: 'GET',
        })
            .then((response) => response.json())
            .then((json) => {
                console.log("戴假髮"+JSON.stringify(json));
                // this.setState({ discounts: json.data })
            })
            .catch((error) => {
                alert(error)
            })
    }

PS:如果想添加回調函式也可封裝的時候新增.