2015-12-04 90 views
10

如何从API定义initialStateRedux React从API创建初始状态

操作

import * as types from '../constants/ActionTypes' 
import jquery from 'jquery' 
import { apiRoot } from '../config.js' 
import Immutable from 'immutable' 
import Random from 'random-js' 

export function fetchLentItemList() { 
    return function(dispatch) { 
    dispatch(fetchLentItems()); 
    jquery.get(`${apiRoot}/api/v1/something/`) 
     .done((data) => { 
     dispatch(fetchLentItems("success", Immutable.fromJS(data))) 
     }) 
     .fail(() => { 
     dispatch(fetchLentItems("error")) 
     }) 
    } 
} 

export function fetchLentItems(status, locations = Immutable.List()) { 
    return { type: types.FETCH_LENT_ITEMS, status, locations } 
} 

减速

import * as types from '../constants/ActionTypes' 
import { combineReducers } from 'redux' 
import Immutable from 'immutable' 

const initialState = { 
    initialLentItems: [], 
    lentItems: [] 
} 

function initialLentItems(state = initialState.initialLentItems, action) { 
    // return state 
    switch (action.type) { 
    case types.FETCH_LENT_ITEMS: 
     switch (action.status) { 
     case 'success': 
      return { 
      initialLentItems: action.locations, 
      lentItems: [] 
      } 
     case 'error': 
      return { 
      initialLentItems: Immutable.List(), 
      lentItems: [] 
      } 
     default: 
      return Object.assign({}, state, { isLoading: true }) 
     } 
    default: 
     return state 
    } 
} 

const rootReducer = combineReducers({ 
    initialLentItems 
}) 

export default rootReducer; 

reducers如果我定义我的initialState这样的,它的工作原理:

initialLentItems: Immutable.fromJS([ 
    { 
     "lent_item_id": 5648, 
     "vendor": "Vendor A", 
     "product": "Product A", 
     "variant": "Variant A", 
    }, 
    { 
     "lent_item_id": 5648, 
     "vendor": "Vendor B", 
     "product": "Product B", 
     "variant": "Variant B", 
    } 
    ]), 

在此先感谢。

+0

什么不适合你? –

+0

我想要的列表不会返回 –

回答

6

在Redux根元素的componentWillMount(被Provider包装并接收商店的元素)中,您可以调度fetchLentItems函数来设置您的初始状态。