zoukankan      html  css  js  c++  java
  • Redux 检测状态树变更

    一 概述

    Redux只是检测引用是否改变。

    如果状态树的某个值是对象、数组等,在reducer中需要生成一个新对象、新数组,才能被Redux检测到变更。

    let fruits = ['apple','banana']; 
    let newFruits = [...fruits,'orange']; // 使用结构赋值,创建新数组。

    如果只是改变对象的属性,或者使用数组的push、splice等方法,Redux会认为状态树没有变更,组件也不会重新渲染。

    Redux、DvaJS(对Redux的封装)都存在这个问题。

    二 代码 

    redux安装包中的redux.js的代码片段。

    function combination() {
        // 此处省略若干代码
    
        var hasChanged = false;
        var nextState = {};
        for (var _i = 0; _i < finalReducerKeys.length; _i++) {
          var _key = finalReducerKeys[_i];
          var reducer = finalReducers[_key];
          var previousStateForKey = state[_key];
          var nextStateForKey = reducer(previousStateForKey, action);
          if (typeof nextStateForKey === 'undefined') {
            var errorMessage = getUndefinedStateErrorMessage(_key, action);
            throw new Error(errorMessage);
          }
          nextState[_key] = nextStateForKey;
          // 只是比较引用是否相同
          hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
        }
        return hasChanged ? nextState : state;
    }
  • 相关阅读:
    Nginx文件下载服务器部署
    Git分支命名规范
    ROS通信介绍
    linux环境设置默认路由的优先级
    Python日志方案
    Python threading Local()函数用法:返回线程局部变量
    Python中websocket的使用示例
    MQTT的Python使用示例
    利用systemback打包个人ISO系统镜像
    Spring Security学习笔记三
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/10470901.html
Copyright © 2011-2022 走看看