Redux实践(1)

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的一个中间件文档.Redux是React的一个数据层,React组件的state有关逻辑处理都...
    smartphp阅读 30,136评论 7 38
  • 学习必备要点: 首先弄明白,Redux在使用React开发应用时,起到什么作用——状态集中管理 弄清楚Redux是...
    贺贺v5阅读 8,940评论 10 58
  • Redux对于React程序是可有可无的吗?当你认识到Redux在编程时给你那种可以掌控一切状态能力的时候,你会觉...
    smartphp阅读 991评论 0 5
  • 前面写了两篇文章《React组件性能优化》《Redux性能优化》,分别针对React和Redux在使用上的性能优化...
    hepeguo阅读 1,767评论 0 5
  • 清微的爱恋(2) 纪清微带领着总经理一行人来到宴会厅,金碧辉煌的大宴会厅已坐满了人,都翘首以盼地要一睹薛家二公子的...
    王婉妮阅读 470评论 0 0