React-Native fetch 网络请求超时 提示

Post image

RN 默认fetch 不能设置超时, 只能死等服务器端设置的超时时间。
假如服务端设置了60s,那移动端等待60s 再响应体验非常差。

解决办法

  npm install  react-native-fetch-polyfill --save
    import fetch from 'react-native-fetch-polyfill';

    fetch(url, {timeout: 30 * 1000})
     .then(response => {
      // a successful response 
    })
     .catch(error => {
    // an error when the request fails, such as during a timeout 
    })

这么写的话略显水平尴尬。可以封装一下

    /****
     * 网络访问。请求写 入api.js 中
     * @param method
     * @param body
     * @returns {{method: *, headers: {ct: *, Accept: string, Content-type: string, Cache-Control: string, Pragma: string, Expires: number}, credentials: string}}
    */
    function createQuery(method, body) {

    const query = {
        "method": method,
        "headers": {
            "ct": global.cache.ct,
            "Accept": "application/json",
            "Content-type": "application/json;charset=UTF-8",
            "Cache-Control": "no-cache, no-store, must-revalidate",
            "Pragma": "no-cache",
            "Expires": 0
        },
        "credentials": "include",
        'timeout': 100,
    }
    if (body) {
        query.body = JSON.stringify(body);
    }
    return query
    }

参考文章



转载请注明:一粒云官方博客 »