likeListReducer.js 2.55 KB
'use strict';
/**
 * ## Imports
 *
 * InitialState
 */
import InitialState from './likeListInitialState';
import Immutable, {List, Record} from 'immutable';

const {
    GO_TO_LIKE_LIST,
    LIKE_LIST_REQUEST,
    LIKE_LIST_SUCCESS,
    LIKE_LIST_FAILURE,
    LIKE_LIST_CLEAN,
} = require('../../constants/actionTypes').default;

const initialState = new InitialState;

export default function likeList(state = initialState, action) {
    if (!(state instanceof InitialState)) {
        return initialState.merge(state);
    }

    switch (action.type) {
        case GO_TO_LIKE_LIST: {
            
            let currentSid = state.sid;
			let newItems = state.items;
			let newSid = currentSid;
			// componentWillUnmount未调用,导致clean操作未进行
			if (action.payload.tryToClean && currentSid > -1 && !state.cleaned) {
				newItems = newItems.pop();
				newSid = newSid - 1;
			}

            let sid = newSid + 1;
			// 获取新的初始状态item
			let item = initialState.item;
			// 设置item的value
			item = item.set('postId', action.payload.postId);
			// items新增item
			newItems = newItems.push(item);
			let nextState =  state.set('sid', sid)
				.set('items', newItems)
                .set('cleaned', false);
			return nextState;
        }

        case LIKE_LIST_REQUEST: {
            let sid = action.payload;
			let nextState =  state.setIn(['items', sid, 'isFetching'], true)
				.setIn(['items', sid, 'error'], null);
            return nextState;
        }

        case LIKE_LIST_SUCCESS: {
            let {sid, json} = action.payload;
            let {lastedTime, list, endReached, total} = json;
            let item = state.items.get(sid);
            item = item.set('isFetching', false)
                .set('error', null)
                .set('lastedTime', lastedTime)
                .set('list', Immutable.fromJS(list))
                .set('endReached', endReached)
                .set('total', total);
            let nextState = state.setIn(['items', sid], item);
			return nextState;
        }

        case LIKE_LIST_FAILURE: {
            let {sid, error} = action.payload;
			let nextState =  state.setIn(['items', sid, 'isFetching'], false)
				.setIn(['items', sid, 'error'], error);
            return nextState;
        }

        case LIKE_LIST_CLEAN: {
            let sid = action.payload;
			if (state.items.size > sid) {
				let items = state.items.pop();
				let nextState =  state.set('sid', sid - 1)
					.set('items', items)
                    .set('cleaned', true);
				return nextState;
			}
        }
    }

    return state;
}