可以将 Immutable.js 映射转换为反应组件内部的对象吗
Is it ok to convert Immutable.js Map to Object inside of react component
我在我的应用程序中使用 redux 和 Immutable.js,我在开始开发项目几周后将 Immutable 添加到应用程序中,因为我不想将当前组件更改为 Immutable 的 . get() 语法 在我的组件内部使用它们之前,我将商店中的不可变映射转换为对象。例如:
@connect((store) => {
return {
login: store.login.toObject(),
user: store.user.toObject()
};
})
这是一种不好的做法吗?这与我的应用程序的性能相关吗?
是的,这是一个非常糟糕的做法。为了让 Immutable 将您的 Immutable 映射转换为 JavaScript,它必须遍历整个对象;这会很慢。此外,您正在失去将 ImmutableJS 与 React 和 Redux 结合使用的大量实际价值。具体来说,您现在不能再通过 shouldComponentUpdate
.
的简单实现来短路不必要的重新渲染
如果你想使用 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()
我在我的应用程序中使用 redux 和 Immutable.js,我在开始开发项目几周后将 Immutable 添加到应用程序中,因为我不想将当前组件更改为 Immutable 的 . get() 语法 在我的组件内部使用它们之前,我将商店中的不可变映射转换为对象。例如:
@connect((store) => {
return {
login: store.login.toObject(),
user: store.user.toObject()
};
})
这是一种不好的做法吗?这与我的应用程序的性能相关吗?
是的,这是一个非常糟糕的做法。为了让 Immutable 将您的 Immutable 映射转换为 JavaScript,它必须遍历整个对象;这会很慢。此外,您正在失去将 ImmutableJS 与 React 和 Redux 结合使用的大量实际价值。具体来说,您现在不能再通过 shouldComponentUpdate
.
如果你想使用 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()