美文网首页react native
Redux在RN中的使用

Redux在RN中的使用

作者: channelRead0 | 来源:发表于2018-05-10 10:56 被阅读339次

    看了网上看了多篇RN中集成redux,现做小结,下一步学习计划,redux和react-navigation的结合使用。

    依赖

    必选

    yarn add redux
    yarn add react-redux
    

    可选,日志、中间件

    yarn add redux-logger
    yarn add redux-thunk
    

    结构

    redux架构一般有4个模块,

    action模块包括 actionType、actions:

    MathType用于声明action中所有的方法

    export const INCREASE = 'increase';
    export const DECREASE = 'decrease';
    export const RESET = 'reset';
    

    MathAction中的每一个方法都会创建一个state并返回,用于区分行动类型

    import * as type from './MathType'
    export function increase() {
        return {
            type: type.INCREASE
        }
    };
    
    export function decrease() {
        return {
            type: type.DECREASE
        }
    };
    
    export function reset() {
        return {
            type: type.RESET
        }
    };
    
    reducers模块接收action,并根据action类型进行相应的处理,返回新的state用于刷新界面

    index,导入的时候直接写包名,会自动导入index

    import { combineReducers } from 'redux';
    import MathReducer from './MathReducer'
    
    export default combineReducers({
        MathReducer
    });
    

    MathReducer最终会返回一个处理完毕的state

    import * as type from '../actions/MathType'
    
    const defaultState = {
        count: 5,
        factor: 1
    }
    
    export default function MathReducer(state = defaultState, action) {
        switch (action.type) {
            case type.INCREASE:
                return {
                    ...state,
                    count: state.count + state.factor
                };
            case type.DECREASE:
                return {
                    ...state,
                    count: state.count - state.factor
                };
            case type.RESET:
                return {
                    ...state,
                    count: 0
                };
            default:
                return state;
        }
    }
    
    store模块可以添加需要的中间件,并引入reducers模块并创建store。

    无中间件

    import {createStore} from 'redux';
    import reducers from '../reducers';
    
    export default store = createStore(reducers)
    

    添加中间件

    import {applyMiddleware, createStore} from 'redux';
    import reducers from '../reducers';
    import thunk from 'redux-thunk'
    import createLogger from 'redux-logger';
    
    const logger = createLogger({
        //options
    });
    
    const store = createStore(
        reducers,
        applyMiddleware(...[thunk, logger]),
    );
    
    export default store;
    

    另一种写法

    import {createStore, applyMiddleware} from 'redux';
    import reducers from '../reducers';
    import thunk from 'redux-thunk';
    import createLogger from 'redux-logger';
    
    const logger = createLogger({
        //options
    });
    
    const middlewares = [thunk,logger ];
    const createSoreWithMiddleware = applyMiddleware(...middlewares)(createStore);
    export default store = createSoreWithMiddleware(reducers);
    
    pages模块,根据最新state刷新页面
    import React, {Component} from 'react';
    import {
        StyleSheet,
        Text,
        View,
        TouchableOpacity
    } from 'react-native';
    import {connect} from 'react-redux';
    import {bindActionCreators} from 'redux';
    import * as Actions from '../actions/MathAction';
    
    class Home extends Component {
    
        _onPressReset() {
            this.props.actions.reset();
        }
    
        _onPressInc() {
            this.props.actions.increase();
        }
    
        _onPressDec() {
            this.props.actions.decrease();
        }
    
        render() {
            return (
                <View style={styles.container}>
                    <Text style={styles.counter}>{this.props.result}</Text>
                    <TouchableOpacity style={styles.reset} onPress={() => this._onPressReset()}>
                        <Text>归零</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.start} onPress={() => this._onPressInc()}>
                        <Text>加1</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.stop} onPress={() => this._onPressDec()}>
                        <Text>减1</Text>
                    </TouchableOpacity>
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            flexDirection: 'column'
        },
        counter: {
            fontSize: 50,
            marginBottom: 70
        },
        reset: {
            margin: 10,
            backgroundColor: 'yellow'
        },
        start: {
            margin: 10,
            backgroundColor: 'yellow'
        },
        stop: {
            margin: 10,
            backgroundColor: 'yellow'
        }
    })
    
    const mapStateToProps = state => ({
        result: state.MathReducer.count
    })
    
    const mapDispatchToProps = dispatch => {
        return {actions: bindActionCreators(Actions, dispatch)}
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(Home);
    

    最后一句用于打通state与页面的通道。

    相关文章

      网友评论

        本文标题:Redux在RN中的使用

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