美文网首页
React-Native爬坑中(Redux)

React-Native爬坑中(Redux)

作者: 逗留 | 来源:发表于2017-09-07 11:52 被阅读50次

    介绍一下我在之前项目中是如何使用redux的。

    redux学习:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
    http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
    http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
    阮一峰老师已经在这几篇文章里讲解的很清楚了,我就不班门弄斧了,这里只是说明一下在项目中的使用。

    首先,安装

    redux:Redux
    react-redux:Redux的作者封装的React专用库
    redux-logger:日志中间件,用于调试
    redux-persist:缓存
    redux-thunk:支持异步dispatch

    安装方法,在package.json文件中的dependencies中添加以下各项
    "react-redux": "^5.0.1",
    "redux": "^3.6.0",
    "redux-logger": "^2.7.4",
    "redux-persist": "^4.0.1",
    "redux-thunk": "^2.1.0"
    然后,执行npm install即可

    也可以分开安装,例如,安装redux
    npm install --save redux (--save代表修改package.json中的dependencies,关于npm的使用可以自行百度,给一个菜鸟教程的链接:http://www.runoob.com/nodejs/nodejs-npm.html

    准备工作完毕后,首先从store开始,新建一个文件,添加以下代码:

    import {applyMiddleware, createStore} from 'redux';
    import thunk from 'redux-thunk';
    import createLogger from 'redux-logger';
    import {persistStore, autoRehydrate} from 'redux-persist';
    import {AsyncStorage} from 'react-native';
    import reducers from '../reducers/index'; //后面解释这个
    
    const logger = createLogger();
    
    let middlewares = [
        thunk,
        logger
    ];
    //解释一下这个写法的意思,可以查看源码,看到applyMiddleware函数,可以传递参数‘{...Function} middlewares The middleware chain to be applied’,然后返回一个以createStore函数为参数的函数,最后会返回一个和createStore函数参数相同的函数,即createAppStore实际是一个function (reducer, preloadedState, enhancer),且这个函数中持有传入的createStore函数,说了一堆函数可能有点乱,其实就是几个闭包
    let createAppStore = applyMiddleware(...middlewares)(createStore);
    
    export default function configureStore(onComplete: ()=>void){
    //同样的查看autoRehydrate,会看到这个函数结构基本和applyMiddleware一样,所以生成store的过程有很多种写法,其实最后得到的结果是一样
        const store = autoRehydrate()(createAppStore)(reducers);
        let opt = {
            storage: AsyncStorage,
            transform: [],
            whitelist: [],
            blacklist: []
        };
        persistStore(store, opt, onComplete);
        return store;
    }
    

    下面实现创建store时用到的reducers,随着项目的增大,reducer会有很多,所以可以将其进行划分,最后合并到一起。例如这里新建一个price.js的reducer文件,在文件中如此实现:

    //数据结构因业务所定
    const initialState = {
        datas: null,
        status: null,
        netMsg: null,
        price: null
    };
    
    import {Net, Process, Response} from '../net/net';
    import Type from '../actions/type';
    export default function priceReducer(state=initialState, action){
        switch(action.type){
            case Type.GETPRICEBASEDATA:
            {
                switch (action.name) {
                    case Process.FETCH_BEGIN:
                        return {
                            ...state,
                            status: Process.FETCH_BEGIN,
                            price: null
                        };
    
                    case Process.FETCH_SUCCESS:
                        return {
                            ...state,
                            datas: action.payload,
                            status: Process.FETCH_SUCCESS,
                            netMsg: action.msg
                        };
    
                    case Process.FETCH_FAIL:
                        return {
                            ...state,
                            status: Process.FETCH_FAIL,
                            netMsg: action.msg
                        };
    
                    default:
                        return state;
                }
            }
            case Type.CALCULATEPRICE:
            {
                switch (action.name) {
                    case Process.FETCH_BEGIN:
                        return {
                            ...state,
                            status: Process.FETCH_BEGIN
                        };
    
                    case Process.FETCH_SUCCESS:
                        return {
                            ...state,
                            price: action.payload,
                            status: Process.FETCH_SUCCESS,
                            netMsg: action.msg
                        };
    
                    case Process.FETCH_FAIL:
                        return {
                            ...state,
                            status: Process.FETCH_FAIL,
                            netMsg: action.msg
                        };
    
                    default:
                        return state;
                }
            }
            default:
                return state;
        }
    
    }
    

    同理新建其它reducer,然后在reducers.js文件中合并

    import { combineReducers } from 'redux';
    import serviceReducer from './service';
    import priceReducer from './price';
    import answersReducer from './answers';
    
    export default combineReducers({
        serviceStore: serviceReducer,
        priceStore: priceReducer,
        answersStore: answersReducer
    });
    

    然后实现action,同样action也应该划分实现,例如price.js的action如下:

    import {Net, Process, Api, Response} from '../net/net';
    import Type from './type';
    
    const changePriceParams = (name, params) => (dispatch, getState) => {
        return dispatch({type: Type.CHANGEPRICEPARAMS, name, params});
    };
    
    const calculatePrice = (params) => (dispatch, getState) => {
        dispatch({type: Type.CALCULATEPRICE, name: Process.FETCH_BEGIN});
        return Net.commonPostModel(Api.CALCULATEPRICEAPI, params, (res)=>{
            if (res.code == 0 || res.code == 999) {
                dispatch({type: Type.CALCULATEPRICE, name: Process.FETCH_SUCCESS, payload: res.data, msg: res.msg})//res.data
            } else {
                dispatch({type: Type.CALCULATEPRICE, name: Process.FETCH_FAIL, payload: null, msg: res.msg})
            }
        })
    };
    
    const getPriceBaseData = () => (dispatch, getState) => {
        dispatch({type: Type.GETPRICEBASEDATA, name: Process.FETCH_BEGIN});
        return Net.commonGetModel(Api.GETPRICEBASEDATAAPI, null, (res)=>{
            if (res.code == 0 || res.code == 999) {
                dispatch({type: Type.GETPRICEBASEDATA, name: Process.FETCH_SUCCESS, payload: res.data, msg: res.msg})//res.data
            } else {
                dispatch({type: Type.GETPRICEBASEDATA, name: Process.FETCH_FAIL, payload: null, msg: res.msg})
            }
        })
    };
    
    export {changePriceParams, calculatePrice, getPriceBaseData};
    

    type.js表示action的标示

    const Type = {
        get GETSERVICEMAIN() {return 'GETSERVICEMAIN'},
        get CHANGEPRICEPARAMS() {return 'CHANGEPRICEPARAMS'},
        get GETPRICERULE() {return 'GETPRICERULE'},
        get SWITCHSECTION() {return 'SWITCHSECTION'},
        get GETPRICEBASEDATA() {return 'GETPRICEBASEDATA'},
        get CALCULATEPRICE() {return 'CALCULATEPRICE'}
    };
    export default Type;
    

    各部分定义完毕后,在根文件如下实现:

    import React, { Component } from 'react';
    import { Provider } from 'react-redux'; //Provider利用了context机制将store对象传递到各个子控件
    
    import configureStore from './store/index';
    let store = configureStore();
    
    import Root from './root';
    
    export default class App extends Component{
        render(){
            return (
                <Provider store={store}>
                    <Root />
                </Provider>
            )
        }
    }
    

    在每个子控件中export时,如下写:

    import { connect } from 'react-redux';
    export default connect()(Root);
    

    另外两个参数可选实现

    import {changePriceParams, calculatePrice, getPriceBaseData} from '../actions/price';
    
    //映射state到props,即获取时直接写this.props.price即可,不再使用this.state(不是不能用this.state,只是和react-redux的设计有悖)
    const mapStateToProps = (state) => {
        return {
            params: state.priceStore.params,
            datas: state.priceStore.datas,
            status: state.priceStore.status,
            netMsg: state.priceStore.netMsg,
            price: state.priceStore.price
        }
    };
    //映射dispatch到props,即使用时this.props.calculatePrice(...)即可
    const mapDispatchToProps = (dispatch) => {
        return {
            changePriceParams: (name, text)=> {
                dispatch(changePriceParams(name, text))
            },
            getPriceBaseData: ()=> {
                dispatch(getPriceBaseData())
            },
            calculatePrice: (params)=> {
                dispatch(calculatePrice(params))
            }
        }
    };
    
    export default connect(
        mapStateToProps,
        mapDispatchToProps
    )(Price);
    

    最后,在控件中即可如下使用:

    render() {
            if (this.props.status === Process.FETCH_BEGIN) {
                showLoading(null);
                this.loading = true;
            } else if (this.props.status === Process.FETCH_FAIL && this.loading) {
                showError(this.props.netMsg);
                this.loading = false;
            } else {
                hideHUD();
            }
            return this._mainView();
        }
    

    在需要计算价格的地方,执行this.props.calculatePrice(params);即可。
    调用相应action,然后传递至reducer修改store,然后更新界面,这些都会自动执行
    这样UI可以专心UI,业务可以专心业务,数据存储专心存储,网络请求专心网络,完美分割。

    然后,针对视图还可以做很多事情,例如如何分离控件与布局,如何自定义navigator,自定义控件,控件间传值等等,RN要学的东西真心不少,这些还只是皮毛,未究其里!

    相关文章

      网友评论

          本文标题:React-Native爬坑中(Redux)

          本文链接:https://www.haomeiwen.com/subject/bqsvjxtx.html