react native 专栏

react-redux相关

2018-06-09  本文已影响0人  JTR354

Flux

Flux的单向数据流

单向数据流框架的始祖

Redux

image

Flux的基本原则是"单向数据流",Redux在此基础上强调三个基本原则:

Redux只有一个Store,其状态结构的设计是Redux的核心问题(Redux对Store进行了封装)

状态只读,修改Store状态通过派发action对象完成和flux相同. 改变状态不是直接修改状态上的值,而是创建一个新的状态对象返回给Redux,由Redux完成新的状态组装(此时,Reducer登场)

纯函数Reducer;

在Redux中每个函数签名如下reducer(state,action);state:当前状态,action:接受到的action对象
Reducer只负责计算状态,却不负责存储状态

React-Redux

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

  1. 获取Store上的状态转化为组件的prop
  2. 将组件中用户动作dispatch给Store
  1. 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
  2. 接收Redux的store作为props,通过context对象传递给子孙组件上的connect

redux-actions插件

createAction 简化action

import * as ActionTypes from './ActionTypes'
import { createAction } from 'redux-actions'
// import { DECREMENT } from './ActionTypes'

// export const increment = (counterCaption) => {
//   return {
//     type: ActionTypes.INCREMENT,
//     counterCaption
//   }
// }
// export const decrement = (counterCaption)=>{
//   return{
//     type:ActionTypes.DECREMENT,
//     counterCaption
//   }
// }

export const increment = createAction(ActionTypes.INCREMENT)
export const decrement = createAction(ActionTypes.DECREMENT)

handleActions 简化Reducer

import * as ActionTypes from './ActionTypes'
import { handleActions } from 'redux-actions'
/* eslint-disable */
// export default (state, action) => {
//   const {counterCaption} = action
//   switch (action.type) {
//     case ActionTypes.INCREMENT:
//       return {...state, [counterCaption]: state[counterCaption] + 1}
//     case ActionTypes.DECREMENT:
//       return {...state, [counterCaption]: state[counterCaption] - 1}
//     default:
//       return state
//   }
// }

export default handleActions({
  [ActionTypes.DECREMENT] (state, action) {
    return {...state, [action.payload]: state[action.payload] - 1}
  },
  [ActionTypes.INCREMENT] (state, action) {
    return {...state, [action.payload]: state[action.payload] + 1}
  }
}, null)
参考:
上一篇下一篇

猜你喜欢

热点阅读