如何将属性设置为初始状态的数组? [英] How to set a property as an array i initial state?

查看:74
本文介绍了如何将属性设置为初始状态的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的减速器中,我通过以下方式设置初始状态:

In my reducer I set initial state by:

const initialState = fromJS({
  results: [],
});

但是,如果我尝试打印结果

However if I try to print results by

initialState.get('results')

initialState.get('results')

我得到了一个不可变地图.

另一方面,如果在我的reducer中(侦听一个动作),我通过

On the other hand if in my reducer (listening to an action) I set the array via

...
case LOAD_SUCCESS:
  return state
     .set('results', []);
...

执行以下操作后,该数组将为实际(不可固定)数组:

the array will be an actual (non-Immutable) array after executing:

state.get('结果')

state.get('results')

(例如在通过重新选择定义的选择器中)

(e.g. in a selector defined via reselect)

为什么?

推荐答案

来自fromJS文档:

将普通的JS对象和数组深层转换为不可变的映射和列表.

Deeply converts plain JS objects and arrays to Immutable Maps and Lists.

也就是说,fromJS({ results: [] })等于Map({ results: List([])})

只要调用state.set('results', []),就将List([])替换为普通数组[].

as soon as you call state.set('results', []), you replace List([]) with plain array [].

这是新手入门的经典陷阱.

This is a classical trap for new starters.

我看到的方式是必须选择始终在此处使用List或纯数组.

The way I see it is you have to choose to either always use List there, or plain array.

列出方式:

初始化:const state = fromJS({results: []})

减少:return state.update("results", list => list.clear())

数组#1 :

初始化:const state = fromJS({results: null})

INIT减少(发送一次,进入初始化状态)return state.set("results", [])

INIT reduce (dispatched once, to init state) return state.set("results", [])

减少:return state.set("results", [1, 2, 3])

数组方法2 :

初始化:const state = Map({results: []})

减少:return state.set("results", [1, 2, 3])

我建议始终使用#2数组方式.它添加了更多的代码,因为您必须为每个州的字段控制List/Map,但是它可以确保您完全得到所需的内容.

I'd recommend to always use Array way #2. It adds more code, as you have to control List / Map for each state's field, but it guarantees you that you get exactly what you want.

最后,它是这样的:

const initialState = Map({ results: [], some_field_as_list: List([]), some_field_as_map: Map([]), ... // etc });

const initialState = Map({ results: [], some_field_as_list: List([]), some_field_as_map: Map([]), ... // etc });

这篇关于如何将属性设置为初始状态的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆