Skip to content

Latest commit

 

History

History
100 lines (85 loc) · 3.9 KB

action-immutable.md

File metadata and controls

100 lines (85 loc) · 3.9 KB

Immutable 实战

Immutable 实战 1(filter、fromJS、includes、first)

let currentConversation = props.conversation;
if (!currentConversation && conversations) {
  currentConversation = conversations
    .filter(item => {
      if (item && item.members) {
        return fromJS(item.members).includes(
          props.remoteUser.user.id.toString()
        );
      } else {
        return false;
      }
    })
    .first();
}

Immutable 实战 2(fromJS、is)

shouldComponentUpdate(nextProps, nextState) {
    let sameState = is(fromJS(this.state), fromJS(nextState));
    let sourceSame = is(fromJS(nextProps.source), fromJS(this.props.source));
    let metaSame = is(fromJS(nextProps.meta), fromJS(this.props.meta));
    let loadingSame = is(fromJS(nextProps.isLoading), fromJS(this.props.isLoading));
    return !sameState || !sourceSame || !metaSame || !loadingSame
  }

Immutable 实战 3(getIn、get)

state => state.getIn(["messages", "isDone"]);
state => state.get("auth");

Immutable 实战 4(updateIn、set)

let messageList = state
  .updateIn(["messages", action.message.id], oldValue => {
    if (oldValue) {
      return [action.message, ...oldValue];
    }
    return oldValue;
  })
  .set("isLoading", false);
return messageList;

Immutable 实战 5(withMutations、mergeDeep)

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case types.GET_CONV:
      return state.withMutations(s =>
        s.set("conv", fromJS(action.data)).set("isLoading", false)
      );
    case types.UPDATE_CONV:
      return state.update("conv", conv => {
        let inConv = false;
        let newConv = conv.map(item => {
          if (item.get("id") === action.data.id) {
            item = item.mergeDeep(fromJS(action.data));
            inConv = true;
          }
          return item;
        });
        if (!inConv) {
          newConv.unshift(fromJS(action.data));
        }
        return newConv;
      });
    default:
      return state;
  }
}