react native 开发应用 数据交互怎么解决?



  • 请问一下 用react native 开发应用 数据交互怎么解决?有控件可以和服务器交互吗?怎么建数据模型



  • 用系统自带的fetch封装的
    Storage是AsyncStorage二次封装的其实就该改了下方法名对数据的json处理

    'use strict'
    
    import Storage from '../utils/Storage';
    import API from '../utils/api';
    
    let status = (result) => {
        if (result.status >= 200 && result.status < 300) {
            return result;
        }
        throw new Error(result.statusText);
    };
    
    export default {
        get(url, data = {}, options) {
            options = {
                keyPrefix: 'isszz',
                caching: 'permanent',
                ...options
            }
            if (data) {
                let params = [];
                Object.keys(data).forEach((param) => {
                    params.push(`${param}=${encodeURIComponent(data[param])}`);
                });
                params = params.join("&");
                url = `${url}?${params}`;
            }
            
            const cacheKey = "cache." + options.keyPrefix + url;
    
            Storage.delete(cacheKey);
    
            if(!options.caching) {
                Storage.getKeys().then(result => {
                    Storage.deletes(result.filter(key => key.startsWith(options.keyPrefix)))
                })
                return fetch(url).then(status).then(result => result.json()).then(result => {
                    return result;
                })
            }
            return Storage.get(cacheKey).then(cached => {
                if(cached) {
                   // console.log("from cached")
                    return cached
                } else {
                    // console.log("from fetch")
                    return fetch(url).then(status).then(result => result.json()).then(result => {
                        if(result.errno == '0') {
                            Storage.set(cacheKey, result);
                        }
                        return result;
                    })
                }
            })
        },
        post(url, data = {}) {
            return fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify(data)
            }).then(status).then((result) => {
                return result.json();
            })
        }
    };
    

登录后回复