使用 Immutable.js 来管理 store 中的数据

本文介绍如何在Redux中使用Immutable.js确保状态不可变性。通过具体示例展示了如何将默认状态转换为Immutable对象,并更新Header组件以反映这些更改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们先来看一下 src/common/header/store 下的reducer ,如下。

import { SEARCH_FOCUS, SEARCH_BLUR } from './actionTypes';

const defaultState = {
    focused: false
};

export default (state = defaultState, action) => {
    if (action.type === SEARCH_FOCUS) {
        let newState = JSON.parse(JSON.stringify(state));
        newState.focused = true;
        return newState;
    }
    if (action.type === SEARCH_BLUR) {
        let newState = JSON.parse(JSON.stringify(state));
        newState.focused = false;
        return newState;
    }
    return state;
}

我们知道,在reducer 函数中,state 是不能修改的。但是,有时候不注意可能就把它的内容改了。总之,immutable.js 就是一个保证属性不变的第三方库。它能帮我们生成一个 immutable 对象(不可改变的)。我们将state 定义为 immutable 对象,那么state 对象如果被修改就会报错了。

github 上 immutable 的网址: https://github.com/immutable-js/immutable-js

我们先下载安装 yarn add immutable

下载好了后,我们就可以来将 state 变为immutable 对象。

打开src/common/header/store 下的reducer

import { SEARCH_FOCUS, SEARCH_BLUR } from './actionTypes';
import { fromJS } from 'immutable';

const defaultState = fromJS({
    focused: false
});

export default (state = defaultState, action) => {
    if (action.type === SEARCH_FOCUS) {
        return state.set("focused", true);
    }
    if (action.type === SEARCH_BLUR) {
        return state.set("focused", false);
    }
    return state;
}

然后,修改一下 Header 组件代码,如下。

const mapStateToProps = (state) => {
  return {
    focused: state.header.get("focused")
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    handleFocus () {
      dispatch(actionCreators.searchFocus());
    },
    handleBlur () {
      dispatch(actionCreators.searchBlur());
    }

  }
}

Done.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值