Redux React 通过 API 创建初始状态

18
如何从API定义initialState操作
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 }
}

Reducers

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

提前致谢。


你具体遇到了什么问题? - vl.lapikov
我想要的列表没有返回 - Kris MP
1个回答

12
在 Redux 根元素的 componentWillMount 生命周期钩子中(该元素被 Provider 包裹并接收 store),您可以分派 fetchLentItems 函数来设置初始状态。

4
如果我们采用这种方法,那么根元素是否变成了为许多不同组件获取状态的垃圾场?如果用户在使用您的站点时永远不会进入许多页面/组件,那么我们难道不会获取不必要的数据吗? - Bob Horn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接