Deng  Zhebin
Deng Zhebin

Reputation: 1262

Using ImmutableJS in React component

There are some cases where react project needs immutableJS to speed up it's performance. But it will screw up what react component code will be written as following code. Instead of the native dot operator , we do have to use immutable instance method(get,getIn,set,setIn) ,which will bloat the code and lost the benfefit of the intellisense and static check from IDE or Typescript.

I know there's an alternative lib seamless-immutable which can save my life.

But are there other simle ways out there in terms of using immutableJS in react component in the way we write the native javascript plain object.

/*Redux part is ommitted and assumed to be all converted to immutable  structure */

class Exam extends Component {
  constructor() {
    super(...arguments);
  }

  componentDidMount() {
    this.props.fetchHomeWorkList(); // ajax fetch data
  }

  render() {
    return this.props.loading || !this.props.homeWorkList ? (
      <Load />
    ) : (
      this.props.homeWorkList.map(homework => (
         <li>{homework.get("title")}</li>
          {homework.get("subHomeWorkList").map(homeWorkEntity => (
            <span>{homeWorkEntity.get("subTitle")}</span>
            <span>{homeWorkEntity.get("content")}</span>
          ))}
        
      ))
    );
  }
}

const mapStateToProps = (state, ownProps) => ({
  homeWorkList: state.getIn(["exam", "homeWorkList"]),
  loading: state.getIn(["exam", "loading"])
});

Upvotes: 0

Views: 310

Answers (1)

mpontus
mpontus

Reputation: 2193

You can use Records but it requires a bit more work than maps:

With Maps

import { fromJS } from 'immutable';

const user = fromJS({
    firstName: "John",
    lastName: "Snow",
});

With Records

import { Record } from 'immutable';

const userFactory = Record({
    firstName: "",
    lastName: "",
});

const user = userFactory({
    firstName: "John",
    lastName: "Snow",
});

To use Records you should define record factories for each type of the leaf node in your store. This is what Record() constructor is used for.

To create a record, you pass JSON object to the record factory. Record instance is similar to a Map but, amongst other things, it allows you to access its fields directly without calling get()

user.get('firstName') === user.firstName

Upvotes: 1

Related Questions