gpt4 book ai didi

javascript - Redux React 从 API 创建初始状态

转载 作者:IT老高 更新时间:2023-10-28 23:11:15 26 4
gpt4 key购买 nike

如何从 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 }
}

reducer

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

提前致谢。

最佳答案

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

关于javascript - Redux React 从 API 创建初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34082153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com