javascript - 使用名称中的变量值访问 redux 存储

标签 javascript reactjs redux react-redux

在我的应用程序中,我将拥有同一对象的副本。由于尽可能保持状态平坦的建议,我基本上在我的状态中创建了多个对象,如下所示:

const initialState = {
    test1: {},
    test2: {},
    test3: {},
}

我设法从我的文件连接到商店,但在访问我想要的对象时遇到问题,特别是因为我只知道索引 (1, 2, 3)。

我已将状态映射到 Prop :

const mapStateToProps = state => {
  return {
    test1: state.test1,
    test2: state.test2,
    test3: state.test3,
  }
}

我尝试按照这些思路做一些事情:

let index = 2;
let infos = this.props.[`test${index}`]

但是这是行不通的,除了在索引上做了一些丑陋的切换,我没有看到另一种获取我想要的对象的方法

最佳答案

您的错误是尝试使用 this.props. 访问状态对象,然后尝试评估变量,您可以执行以下操作:

const index = 2;
const infos = this.props[`test${index}`];

关于javascript - 使用名称中的变量值访问 redux 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58283105/

相关文章:

javascript - 将 JavaScript 的映射与对象的方法一起使用

javascript - react : Drag div with minimal footprint and with model/view separation

reactjs - 如何在按钮单击时禁用 <react-date-picker> 组件

javascript - HTML5 Canvas 变形

javascript - removeAttr ("style") 不起作用

javascript - 用于突出显示功能的更高效的 JavaScript 代码?

reactjs - React 根据 props 更改 className

javascript - 链接 axios 请求

javascript - 更新 redux 商店上的 isLoading 字段

javascript - 在Reducer中使用扩展语法