2015-12-04 39 views
10

Cách xác định initialState từ API?Redux React tạo trạng thái ban đầu từ API

Actions

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 } 
} 

Hộp số

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; 

Trong reducers nếu tôi định nghĩa của tôi initialState như thế này, nó hoạt động:

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", 
    } 
    ]), 

Xin cảm ơn trước.

+0

Chính xác thì điều gì không phù hợp với bạn? –

+0

danh sách tôi muốn không được trả lại –

Trả lời

6

Trong phần componentWillMount của phần tử gốc Redux của bạn (phần được bọc bởi Provider và nhận được cửa hàng), bạn có thể gửi hàm fetchLentItems để thiết lập trạng thái ban đầu của mình.

Các vấn đề liên quan