Redux学习(一)之添加Redux到自己的项目

关于redux的重要性我就不再详细讲解,直接进入今天的正题,添加redux到自己的项目中
1. react-native init Reading_Redux 初始化一个rn项目,目录结构如下其中app是我手动添加的
WX20170105-135339.png

  1. 新建redux文件夹,同时在其下创建actions、constant、containers、reducer、store文件夹,用处稍后会讲解。

3.创建index.js

......
class Index extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
       /** state,add,del是哪里来的?不要急 **/
        const {state}=this.props;
        const {add,del,init}=this.props.actions;
        return (
            <View style={styles.container}>
                <Text>Redux-加法运算</Text>
                <View style={styles.item}>
                    <Text>合 计:</Text>
                    <Text style={{color: 'red'}}>{state.sum}</Text>
                </View>
                <View style={[styles.item, {top: 10}]}>
                    <TouchableWithoutFeedback onPress={add} >
                        <View style={styles.touch}>
                            <Text style={styles.but}>+</Text>
                        </View>
                    </TouchableWithoutFeedback>
                    <TouchableWithoutFeedback onPress={del}>
                        <View style={styles.touch}>
                            <Text style={styles.but}>-</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
            </View>
        );
    }
}
......

看注释、看注释、看注释
4.在actions中创建IndexAction.js

import * as types from '../constant/ActionTypes';
//数量加
export function add() {
    return {
        type: types.INDEX_ADD
    }
}
//数量减
export function del() {
    return {
        type: types.INDEX_DEL
    }
}

原来是add和del在这里做了定义,不难看出每个fun都return了一个常量type,接下来我们就来创建接受这个type值的类IndexReducer.js
5.在reducer中创建IndexReducer.js

import * as types from '../constant/ActionTypes';

const initialState = {
    sum:0
};
export default function IndexReducer(state = initialState, action = {}) {
    switch (action.type){
        case types.INDEX_ADD:
            return {
                ...state,
                sum:state.sum+1
            };
            break;
        case types.INDEX_DEL:
            return {
                ...state,
                sum:state.sum-1
            };
            break;
        case types.INDEX_INIT:
            return {
                ...state,
                sum:action.param!=undefined
            };
            break;
        default:
            return state;
    }
}

我们可以看到真正的逻辑操作是在这里完成的,根据不同的type值我们处理了sum的结果并且return了出去,想想index.js中我们显示的最终结果是不是sum,原来它是定义在这里的,到此为止index中我们的那个疑问都有了结果,可是这些都是如何连接在一起的?接下来我们就开始redux的重点,绑定state到我们自己的页面。

这里还有一种方式就是将所有的逻辑操作放在我们的action中,然后将结果和type一起返回,然后在reducer中只是接受值并且return就可以了。

6.创建状态收集类RootReducer.js

import { combineReducers } from 'redux';
import IndexReducer from './IndexReducer';
const RootReducer = combineReducers({
    IndexReducer,
   /** 添加其他自己定义好的reducer **/
});
export default RootReducer;

如果你觉的这段代码理解起来有点抽象,你可以把他理解为有一个树��、而每一个reducer就是一个枝干,这个类就是将所有的枝干连接到主干的一个过程。这是一个固定格式直接copy也是可以的。

7.上一步我们创建出了状态收集类或树,这一步我们就把这个树种植到某一块区域让他茁壮成长,这个地方就是redux的store。
新建configure-store.js

import {createStore, applyMiddleware} from 'redux';
import  rootReducer from '../reducer/RootReducer';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const createLogger = require('redux-logger');
/** 在开发者模式下开启打印日志功能**/
if (process.env.NODE_ENV === 'development') {
    const logger = createLogger();
    //redux 日志打印
    middlewares.push(logger);
}
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore);
/**创建configureStore方法,开辟一块空地store,同时把树rootReducer种植进去,initialState为初始状态**/
export default function configureStore(initialState) {
    const store = createStoreWithMiddleware(rootReducer, initialState);
    return store;
}

到此redux算是配置完成了,接下来我们将这个树指定到我们的项目中,同时将每一个枝干和我们的页面做关联。
8.在Root.js中将store绑定到我们的项目中

......
import { Provider } from 'react-redux';
import IndexContainer from './redux/containers/IndexContainer';
import configureStore from './redux/store/configure-store';
const store =configureStore();
const Root = () => (
    <Provider store={store}>
        <IndexContainer />
    </Provider>
);
export default Root;

9.在IndexContainer中绑定IndexReducer、IndexAction到我们的index页面

......
import Index from '../../pages/Index';
import {bindActionCreators} from 'redux';
import * as IndexAction from '../actions/IndexAction';
class IndexContainer extends React.Component {
    render() {
        return (
            <Index
                {...this.props}
            />
        );
    }
}
/** 绑定IndexReducer、IndexAction **/
export default connect(state => ({
        state: state.IndexReducer
    }),
    (dispatch) => ({
        actions: bindActionCreators(IndexAction, dispatch)
    })
)(IndexContainer);

这样index中的的疑问就彻底解决了,是不是很开森。

总结一下:其实redux的使用并没有那么难,伙伴们照着我的这几个步骤走下来就可以了,对于redux的实现原理我会在之后的文章中具体介绍。

最后我把我的package.json中的代码也贴出来

{
    "name": "Reading_Redux",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start"
    },
    "dependencies": {
        "react": "15.4.1",
        "react-native": "0.40.0"
    },
    "devDependencies": {
        "react-redux": "^4.4.5",
        "redux": "^3.5.2",
        "redux-logger": "^2.6.1",
        "redux-thunk": "^2.1.0"
    }
}

项目地址:GitHub

博主QQ小窝、期待你的到来 581621024

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值