简体   繁体   中英

Is it ok to convert Immutable.js Map to Object inside of react component

I am using redux and Immutable.js in my application, I added Immutable to the app a few weeks after I started developing the project and as I didn't want to change my current components to the Immutable's .get() syntax I converted the Immutable Maps in my store to Objects before using them inside of my components. Ex.:

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

Is it a bad practice?Would that be relevant for the performance of my app?

Yes, this is a VERY bad practice. In order for Immutable to convert your Immutable maps to JavaScript it has to walk the entire object; this is going to be slow. Also, you are losing a huge amount of the actual value of using ImmutableJS with React and Redux. Specifically, you now can no longer short circuit needless re-renders with a simple implementation of shouldComponentUpdate .

If you want to use ImmutableJS Maps , but don't want to have to use get syntax, you can use Records . They have all the functionality of Maps , except for arbitrary-value keys (which accessor syntax wouldn't work on anyways).

A brief example:

// 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM