在 reducer 中使用变量作为对象键 [英] Use a variable as an object key in reducer

查看:41
本文介绍了在 reducer 中使用变量作为对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构建对象时遇到问题.我有一个字符串(在本例中称为SKU"),它通过 action 作为 action.name 传入.

I'm having trouble constructing an object. I've got a string (called "SKU" for this example) and it's coming through action as action.name.

我在 reducer 函数中拥有所有可用的东西,但我需要将硬编码的 SKU 更改为 action.name,但显然这在 JS 中是不可能的.我已经尝试了 action.nameaction['name'] 和其他变体,但我被卡住了.

I have everything available in the reducer function but I need to change the hardcoded SKU to action.name, but obviously that's not possible in JS. I've tried action.name, action['name'] and other variations and I'm stuck.

解决方法是什么?任何帮助表示赞赏!谢谢.

What is the work around? Any help appreciated! Thanks.

这是一些代码,以便您可以看到发生了什么:

Here's some code so you can see what's going on:

日期改变时触发的函数...

handleChange(date) {
  this.props.addDate(date, this.props.dashboardName);
}

mapDispatch 连接在组件导出底部...

const mapDispatchToProps = dispatch => {
  return {
    addDate: (date, name) => dispatch({
      type: 'ACTION_DASHBOARD_ADD_DATE',
      date,
      name
    })
  };
};

动作创建者...

export function DashboardDate() {
  return {
    type: ACTION_DASHBOARD_ADD_DATE
  };
}

reducer 开关的情况...

case ACTION_DASHBOARD_ADD_DATE: {
      var filter = {};
      filter[action.name] = action.date;
      return {
        ...state,
        dashboard: {
          ...state.dashboard,
          // Below SKU needs to be the value of action.name
          SKU: {
            // Below too, action.name
            ...state.dashboard.SKU,
            filter
          }
        }
      };
    }

推荐答案

我不是 100% 确定您想让 sku 出现在您的代码中的哪个位置,但是您可以创建一个对象像这样的计算属性名称:

I'm not 100% sure where in your code you want to have the sku appear, but you can create an object with a computed property name like this:

const obj = {
    [action.name]: action.payload
};

console.log(obj); // { "sku": "abcd" }

计算属性名称是 ES2015 (ES6) 功能.

Computed property names are an ES2015 (ES6) feature.

这篇关于在 reducer 中使用变量作为对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆