CNode

给 redux 一个标准的 reducer

分享
Mmagicdawn发布于9 年前最后回复9 年前10 回复8986 浏览0 收藏

主页 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,
}
keytyperemark
typeStringif type starts with STANDARD_MERGE_STATE, the action payload will be merged to state
payloadObjectthe data need to be merged
standardBooleanif 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)

I
i5ting#1·9 年前

有点意思~

Y
yinxin630#2·9 年前

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

M
mlyknown#4·9 年前

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

T
TonyYu2015#6·9 年前

学习下

M
malash#7·9 年前

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

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

Y
yinxin630#8·9 年前
引用 magicdawn@yinxin630 你这个工程挺复杂的...

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

M
malash#10·9 年前
引用 magicdawn@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

参与回复
登录后即可参与回复。登录