【问题标题】:How to pass values of an array across properties of different array objects如何跨不同数组对象的属性传递数组的值
【发布时间】:2020-02-08 18:56:48
【问题描述】:
  1. 列表项

我有一个具有这种结构的 redux 商店

const INITIAL_STATE = {
    currentData: [
        {
            title: 'Total Insurance Bought',
            img: 'insurance-bought.svg',
            bg: 'insurance-shield',
            data: '',
        },
        {
            title: 'Total Amount of Claims',
            img: 'amount of claims icon.svg',
            bg: 'amount-of-claims',
            data: '',
        }
    ]
} 

这是我的reducer函数的当前结构

const summaryReducer = (state = INITIAL_STATE, action ) => {
    switch(action.type){
        case 'SET_SUMMARY_DATA':
            return {
                ...state,
                currentData: {
                    ...state.currentData,
                    data: action.payload
                }
            }
        default: 
            return state
    }
}

我想将 action.payload 中这个数组的值传播到初始状态的每个数据属性中,同时返回整个状态。

[ 0 , 20000 ]

我希望我的输出是

const INITIAL_STATE = {
    currentData: [
        {
            title: 'Total Insurance Bought',
            img: 'insurance-bought.svg',
            bg: 'insurance-shield',
            data: '0',
        },
        {
            title: 'Total Amount of Claims',
            img: 'amount of claims icon.svg',
            bg: 'amount-of-claims',
            data: '20000',
        }
    ]
} 

【问题讨论】:

  • [ 0 , 20000 ] - 这些值中的哪一个对应于 Total Insurance Bought 和 Total Amount of Claims?你希望你的最终输出是怎样的?
  • 0 应该去 Total insurance and 20000 to total amount of claim
  • 我已经发布了我的解决方案,希望对您有所帮助!

标签: javascript reactjs object redux


【解决方案1】:

如果您当前的数据总是有两个数组项,并且如果预期的有效负载将有两个按预期顺序排列的元素,您可以这样做。

case 'SET_SUMMARY_DATA':
  return {
     ...state,
     currentData: currentData.map((currentItem, index) => {
       currentItem.data = action.payload[index];
       return currentItem;
     })
  }

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 2022-08-17
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多