[英]Add item to an element of an array in Redux
I'm attempting to get my redux reducer to perform something like this: 我正在尝试让我的redux减速器执行以下操作:
however, I am outputting the following: 但是,我输出以下内容:
The following is the code I am using to attempt this. 以下是我用来尝试此操作的代码。 I've attempted to include action.userHoldings in the coinData array, however, that also ends up on a different line instead of within the same object.
我试图将action.userHoldings包含在coinData数组中,但这也最终会出现在不同的行而不是同一对象内。 My objective is to get userHoldings within the 0th element of coinData similar to how userHoldings is in the portfolio array in the first image.
我的目标是使coinData的第0个元素内的userHoldings与第一个图像中的投资组合数组中的userHoldings相似。
import * as actions from '../actions/fetch-portfolio';
const initialState = {
coinData: [],
userHoldings: ''
};
export default function portfolioReducer(state = initialState, action) {
if (action.type === actions.ADD_COIN_TO_PORTFOLIO) {
return Object.assign({}, state, {
coinData: [...state.coinData, action.cryptoData],
userHoldings: action.userHoldings
});
}
return state;
}
I guess you want to do something like this. 我想你想做这样的事情。
return Object.assign({}, state, {
coinData: [ {...state.coinData[0],cryptoData: action.cryptoDatauserHoldings: action.userHoldings}, ...state.coinData.slice(1) ],
});
}
slice(1) is to get all elements except 0th. slice(1)将获取除第0个元素之外的所有元素。 For the first element, you can construct object the way you like.
对于第一个元素,您可以按自己喜欢的方式构造对象。 This should do the trick.
这应该可以解决问题。 Slice returns a new array unlike splice/push or others so safe to use in reducers.
Slice会返回一个新的数组,这与拼接/推入或其他在变径器中安全使用的数组不同。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.