给 redux 一个标准的 reducer
发布于 7 年前 作者 magicdawn 6929 次浏览 来自 分享

主页 https://github.com/magicdawn/redux-standard-reducer 简单点就是这么一个思想:

  • 不根据 action 的类型, 去实现 reducer 去改变 state,
  • 而是加一个 standard reducer, 然后在 action 加一个标识, 我这里加的 standard:true , 根据 action.payload 合并到 state, 由 action 来决定 state 的样子, 而不是reducer.

喜欢请 star, 有想法可以交流下. 个人愚见, 不对请指正. 😂

--------------下面是 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)

Action

action = {
  type,
  payload,
  standard,
}
key type remark
type String if type starts with STANDARD_MERGE_STATE, the action payload will be merged to state
payload Object the data need to be merged
standard Boolean if action.standard is true, the action payload will be merged to state

more see the test/simple.js

Changelog

CHANGELOG.md

License

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

10 回复

有点意思~

https://github.com/yinxin630/fiora/blob/next/src/client/state/reducer.js 我这个reducer跟你想法类似呢, 定义一套通用reducer给action用…

@yinxin630

你这个工程挺复杂的…

standard这个字段没有太大必要啊,最后reducer应该是 standrardReducer 和 CustomizedReducer merge的结构就好了

@mlyknown 考虑到可能不止两个 reducer, 每个处理好自己的部分就行吧

@magicdawn 我的store是immutable的, 然后发现会有些reducer结构基本一致, 仅仅是操作的字段不同, 于是就考虑写一套通用的增删改查reducer供action调用, 感觉这样子reducer会很好维护, 而且后期很少需要修改.

其中这种做法相当于直接修改state,毕竟Redux对于很多简单的场景过于复杂了,能够直接修改state会方便很多。

推荐尝试下Noflux:https://github.com/nofluxjs/noflux 。相比于使用lodash.mergewith实现,利用Copy on write可以获得更好的性能,而且不需要引入Redux,用法更简单些

@malash

看着使用起来挺方便的, 就是使用了 forceUpdate, 不知性能如何?

@magicdawn 性能优化主要有写时复制(copy-on-write)和部分监听:

1、写时复制相当于在Redux中使用 … 创建新state,可以以最小的成本更新state,而且状态是immutable的。

2、部分监听在这里有详细的介绍 https://noflux.js.org/zh/advanced/connect.html,它可以实现状态变更时只 forceUpdate 必要的组件。内部使用了自己实现的监听树,有能尚可,相关的benchmark: https://github.com/nofluxjs/noflux-state/blob/master/benchmark/index.js

回到顶部