可以将Immutable.js Map转换为react组件内的Object

时间:2016-09-25 06:36:29

标签: javascript reactjs redux react-redux immutable.js

我在我的应用程序中使用了redux和Immutable.js,在我开始开发项目几周后,我在应用程序中添加了Immutable,因为我不想将当前组件更改为Immutable' s .get()语法我在我的商店中将不可变地图转换为对象,然后在我的组件中使用它们。例:

@connect((store) => {
  return {
    login: store.login.toObject(),
    user: store.user.toObject()
  };
})

这是一种不好的做法吗?这与我的应用程序的性能有关吗?

2 个答案:

答案 0 :(得分:4)

是的,这是一个非常糟糕的做法。为了让Immutable将您的不可变地图转换为JavaScript,它必须遍历整个对象;这会很慢。此外,您正在失去使用Reutable和Redux使用ImmutableJS的大量实际价值。具体来说,您现在不能再使用shouldComponentUpdate的简单实现来短路不必要的重新渲染。

答案 1 :(得分:2)

如果您想使用ImmutableJS Maps,但又不想使用get语法,则可以使用Records。它们具有Maps的所有功能,除了任意值键(访问器语法无论如何都不会起作用)。

一个简短的例子:

// Specify the allowed fields and their default values
const TodoListState = Immutable.Record({ todos: undefined, filter: undefined })

// Instantiate the record using `new` and an object with the desired KV mapping
const initialTodoState = new TodoListState({ 
  todos: Immutable.List(),
  filter: undefined, // this is already the default, but I prefer being explicit
})

const initialTodos = initialTodoState.todos // List()
相关问题