react native 使用 immutable

react native + redux + immutable

举一个加减的小例子
首先,安装依赖:
yarn add immutable redux-immutable 
使用 redux 时,需要改 reducer:
import { combineReducers } from 'redux-immutable'
import count from './count'
export default combineReducers({
  count
})
然后创建 count.js 组件,用来显示效果
import React, { PureComponent } from 'react'
import { Text, View } from 'react-native'
import { connect } from 'react-redux'
import { decrement, increment } from '../action/count'

class Counter extends PureComponent {
  render() {
    return (
      <View>
        <Text onPress={this.props.decrement}> decrement </Text>
        <Text> {this.props.count.get('num')} </Text>
        <Text> {this.props.count.get('name')} </Text>
        <Text> {this.props.count.get('friend')} </Text>
        <Text onPress={this.props.increment}> increment </Text>
      </View>
    )
  }
}

const mapState = state => {
  return {
    count: state.getIn(['count'])
  }
}
export default connect(mapState, { decrement, increment })(Counter)
省略配置 store.js 和 action 的步骤,直接来看 reducer 中的 count.js
import actionTypes from '../action/actionTypes'
import { fromJS } from 'immutable'


const initState = fromJS({
  num: 0,
  name: '大明',
  friend: '小红',
})

export default (state = initState, action) => {
  console.log(state)
  console.log(initState)
  switch (action.type) {
    case actionTypes.decrement:
      return (
        state
          .update('num', v => v - 1)
          .set('name', '大力')
          .set('friend', '小茜')
      )
    case actionTypes.increment:
      return (
        state
          .update('num', v => v + 1)
          .set('name', '小周')
          .set('friend', '大海')
      )
    default:
      return state
  }
} 
运行项目
运行时点击 decrement 或者 increment ,数字和文字变化的同时,initState 不会发生改变,变化的只有 state
使用 immutable 需要注意的是:
在 reducers 文件夹下的 count.js 传出的 count 对象是一个 immutable 对象,而 connect 组件接收到的是一个包含多个 immutable 对象的 immutable 对象,所以在使用 get(‘count’) 方法后得到的是 immutable对象 count,在组建 porps 中使用时,还应该再使用 get() 方法去取得 count 中的相应数据。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值