美文网首页
Redux实践(1)

Redux实践(1)

作者: Syanbo | 来源:发表于2017-09-05 15:41 被阅读98次

redux 新的尝试

  1. normalizr
  2. redux-actions
  3. redux-persist
  4. redux-thunk
  5. reselect

一些思考

  • reducers 维护一套自定义数据模型(Model)和界面状态(UI)
  • Model 使用 normalizr 辅助设计数据模型
  • UI 一般的网络状态等等其他

connectComponent

给connect做一个中间层便于默认参数统一配置

import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import actions from "./actions";

const options = {
    withRef: true
};
const defaultMapStateToProps = (state, props) => ({});
const defaultMapDispatchToProps = (dispatch, props) => ({
    actions: bindActionCreators(actions, dispatch)
});
const defaultMergeProps = (stateProps, dispatchProps, ownProps) => (
    Object.assign({}, ownProps, stateProps, dispatchProps)
);

const getMapStateToProps = (makeSelector) => () => (state, props) => ({
    data: makeSelector()(state, props),
});

export default ({makeSelector, mapStateToProps, mapDispatchToProps, mergeProps}) => (
    connect(
        mapStateToProps || makeSelector && getMapStateToProps(makeSelector) || defaultMapStateToProps,
        mapDispatchToProps || defaultMapDispatchToProps,
        mergeProps || defaultMergeProps,
        options
    )
);

reselect (选择器)

  • 每当组件更新时都会重新计算 todos。如果 state tree 非常大,或者计算量非常大,每次更新都重新计算可能会带来性能问题。reselect 能帮你省去这些没必要的重新计算。

  • reselect 提供 createSelector 函数来创建可记忆的 selector。createSelector 接收一个 input-selectors 数组和一个转换函数作为参数。如果 state tree 的改变会引起 input-selector 值变化,那么 selector 会调用转换函数,传入 input-selectors 作为参数,并返回结果。如果 input-selectors 的值和前一次的一样,它将会直接返回前一次计算的数据,而不会再调用一次转换函数。

const makeSelector = () => createSelector(
    [
        (state, props) => {
            let {home, Goods, Users} = state;
            return denormalize(home.list, GoodsList, {Goods, Users})
        }
    ],
    (data) => data
);

normalizr

为什么使用
设计模式假设为后台与前台对应,前台维护自己的一套数据模型,应用数据架构复杂的情况下,后台数据不理想而产生的影响

方法
  • normalize
  • denormalize
  • schema
    • Array
    • Entity
    • Object
    • Union
    • Values

相关文章

网友评论

      本文标题:Redux实践(1)

      本文链接:https://www.haomeiwen.com/subject/vinujxtx.html