我有一个可供选择的“比较器”列表。我想在标题下方显示一个比较器中的帐户数量。我能够创建一个函数来获取帐户并获取大小。但是,它只在我第二次加载页面时有效。如果我第一次加载它,结果总是显示 0。我如何确保在我第一次加载页面时,数据被正确获取和加载?import { SET_COMPARATOR_PRODUCTS_AMOUNT, GET_COMPARATORS_INSTITUTIONS, GET_COMPARATOR_ACCOUNTS,} from '../types/Comparators';import Config from 'react-native-config';import {AxiosInstance} from '../api/AxiosInstance';export const getAmount = comparator => dispatch => { AxiosInstance.get('/comparators/' + comparator, { headers: { 'X-Comparator-API-KEY': Config.COMPARATOR_API_KEY, 'content-type': 'application/json', }, }).then(res => { dispatch({ type: SET_COMPARATOR_PRODUCTS_AMOUNT, payload: { comparator: comparator, amount: res.data.length, }, }); });};import { SET_COMPARATOR_PRODUCTS_AMOUNT, GET_COMPARATORS_INSTITUTIONS, GET_COMPARATOR_ACCOUNTS,} from '../types/Comparators';const INITIAL_STATE = { accountsAmount: {}, institutions: [], accounts: [],};export default (state = INITIAL_STATE, action) => { switch (action.type) { case SET_COMPARATOR_PRODUCTS_AMOUNT: var accountsAmount = state.accountsAmount; accountsAmount[action.payload.comparator] = action.payload.amount; return Object.assign({}, state, {accountsAmount: accountsAmount}); case GET_COMPARATORS_INSTITUTIONS: return { ...state, institutions: action.payload, }; case GET_COMPARATOR_ACCOUNTS: return { ...state, accounts: action.payload, }; default: return state; }};
1 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
可能是因为您改变了状态,请改为尝试以下操作:
case SET_COMPARATOR_PRODUCTS_AMOUNT:
//make a shallow copy
var accountsAmount = {...state.accountsAmount};
//mutate the shallow copy
accountsAmount[action.payload.comparator] =
action.payload.amount;
return Object.assign({}, state, {
accountsAmount,
});
添加回答
举报
0/150
提交
取消