redux standard reducer 新增 immutability-helper 集成, 使用 action.update 操作 state
发布于 1 年前 作者 magicdawn 1869 次浏览 来自 分享

RT, 主页 https://github.com/magicdawn/redux-standard-reducer 前面我在这里介绍了 https://cnodejs.org/topic/5999aca24e3c4e5a7021b267 redux-standard-reducer 使用了 action.payload 来合并到 state, 但使用 lodash.mergeWith 自己写的 customMerger 毕竟有些 tricky. 还会出现一些问题, 例如 v0.0.3 之前每次 merge 完之后, 没有改动的 state 子树都变了, 导致 connect 到 react 组件的时候, 在实现 componentWillReceiveProps 时使用 this.props.xxx !== nextProps.xxx 的本意改变了 现在 v0.1.0 版本可以使用 immutability-helper 使用 action.update 来操作 state, 如

import assert from 'assert'
import reduceReducers from 'reduce-reducers'
import { combineReducers } from 'redux'
import standardReducer from '../src/index'

/* eslint no-extra-semi: off */

describe('immutability-helper', function() {
  let reducer
  let state

  beforeEach(() => {
    reducer = reduceReducers(
      standardReducer,
      (state = { arr: [] }, action) => state,
      combineReducers({
        partial1(state = { value: 1, foo: 'bar-1' }, action) {
          return state
        },

        partial2(state = { value: 2, foo: 'bar-2' }, action) {
          return state
        },
      })
    )

    // init
    state = {}
    state = reducer(state, { type: 'init' })
    state.partial1.value.should.equal(1)
    state.partial2.value.should.equal(2)
  })

  it('it works', function() {
    state = reducer(state, {
      type: 'UPDATE_PARTIAL_1',
      standard: true,
      update: {
        partial1: {
          foo: { $set: 'updated-foo-1' },
        },
      },
    })
    state.partial1.foo.should.equal('updated-foo-1')
  })
})

—更新版 readme-----

redux-standard-reducer

A redux reducer for standard action that merge data to state

Build Status Coverage Status npm version npm downloads npm license

Install

$ npm i redux-standard-reducer --save

Usage

// suppose all business reducer exits in app/reducers/
import reducer from './app/reducers'

import standardReducer from 'redux-standard-reducer'
import reduceReducers from 'reduce-reducers'

// reducer for createStore
const finalReducer = reduceReducers(
  standardReducer,
  reducer
)

const store = createStore(initialState, finalReducer, enhancers)

enable this reducer

use any one of these:

  • make action.type starts with STANDARD_MERGE_STATE, this reducer will handle the action
  • make action.standard = true, this reducer will handle the action

Action with payload

action = {
  type,
  standard,
  payload: {...},
}
key type remark
payload Object the data need to be merged to the store.state

Action with update

action = {
  type,
  standard,
  update: {...},
}
key type remark
update Object the update operation, will pass to immutability-helper, equal to immutabilityHelper(store.state, action.update)

Changelog

CHANGELOG.md

License

the MIT License http://magicdawn.mit-license.org

3 回复

消灭0回复…

@magicdawn 棒棒哒,以后是react一哥啊

@i5ting 哈哈哈😄

回到顶部