前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react-native添加redux支持

react-native添加redux支持

作者头像
xiangzhihong
发布2018-02-06 16:25:40
1.6K0
发布2018-02-06 16:25:40
举报
文章被收录于专栏:向治洪

redux简介

redux是一个用于管理js应用状态的容器。redux出现时间并不是很长,在它出现之前也有类似功能的模块出现,诸如flux等等。redux设计的理念很简单,似乎最初这个开发团队就有让redux可以方便融入在server, browser, mobile client端的打算。目前在github上redux-*的第三方中间件、插件越来越多。如果react项目中想使用redux,那么就有react-redux插件来完成配合。

项目实例

这里写图片描述
这里写图片描述

如图所示,这是一个非常简单的例子:只有两个文件package.json和index.ios.js, 点击加1按钮数字值就会+1, 点击减1按钮数字值就会-1, 点击归零按钮则数字值置为0。

index.ios.js代码如下:

代码语言:javascript
复制
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

class Main extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 5 }
  }

  _onPressReset() {
    this.setState({ count: 0 })
  }

  _onPressInc() {
    this.setState({ count: this.state.count+1 });
  }

  _onPressDec() {
    this.setState({ count: this.state.count-1 });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.state.count}</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'
  }
})

AppRegistry.registerComponent('Main', () => Main);

添加redux

1,要想使用redux的相关功能,首先需要添加redux相关依赖库。直接使用npm install 命令安装。默认情况下会将安装的信息保存到package.json里面。

代码语言:javascript
复制
"dependencies": {
    ...
    "react-redux": "^4.4.5",
    "redux": "^3.5.2",
    "redux-logger": "^2.6.1"
},

2,创建actionsTypes.js用来定义所有的action名称, 定义三个常量action, 分别表示增加、减小、重置。

代码语言:javascript
复制
export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';
export const RESET = 'RESET';

actions.js代码如下:

代码语言:javascript
复制
import { INCREASE, DECREASE, RESET } from './actionsTypes';

const increase = () => ({ type: INCREASE });
const decrease = () => ({ type: DECREASE });
const reset = () => ({ type: RESET });

export {
    increase,
    decrease,
    reset
}

3,创建reducers.js, 根据需要在收到相关的action时操作项目的state。

代码语言:javascript
复制
import { combineReducers } from 'redux';
import { INCREASE, DECREASE, RESET} from './actionsTypes';

// 原始默认state
const defaultState = {
  count: 5,
  factor: 1
}

function counter(state = defaultState, action) {
  switch (action.type) {
    case INCREASE:
      return { ...state, count: state.count + state.factor };
    case DECREASE:
      return { ...state, count: state.count - state.factor };
    case RESET:
      return { ...state, count: 0 };
    default:
      return state;
  }
}

export default combineReducers({
    counter
});

4,创建store.js。

代码语言:javascript
复制
import { createStore, applyMiddleware, compose } from 'redux';
import createLogger from 'redux-logger';
import rootReducer from './reducers';

const configureStore = preloadedState => {
    return createStore (
        rootReducer,
        preloadedState,
        compose (
            applyMiddleware(createLogger())
        )
    );
}

const store = configureStore();

export default store;

至此,redux的几大部分都创建完毕, 下一步就是引入项目中。 5,在项目中引入上面的文件。创建app.js和home.js app.js代码如下:

代码语言:javascript
复制
import React, { Component } from 'righteact';
import { Provider } from 'react-redux';
import Home from './home';
import store from './store';

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Home/>
      </Provider>
    );
  }
}

修改home.js

代码语言:javascript
复制
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';
import { connect } from 'react-redux';
import { increase, decrease, reset } from './actions';

class Home extends Component {
  _onPressReset() {
    this.props.dispatch(reset());
  }

  _onPressInc() {
    this.props.dispatch(increase());
  }

  _onPressDec() {
    this.props.dispatch(decrease());
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.props.counter.count}</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({
  ...
})

const mapStateToProps = state => ({
    counter: state.counter
})

export default connect(mapStateToProps)(Home);

最后在index.ios.js添加app引入。

代码语言:javascript
复制
import { AppRegistry } from 'react-native';
import App from './app';

AppRegistry.registerComponent('Helloworld', () => App);

这样,我们就将redux引入到了React Native中。commond+R运行, command+D打开chrome浏览器调试, 可以看到redux-logger把每个action动作都打和state的前后变化印出来。

这里写图片描述
这里写图片描述

参考:深入理解redux

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-05-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • redux简介
  • 项目实例
    • 添加redux
    相关产品与服务
    消息队列 TDMQ
    消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档