【问题标题】:How to use global value when reading nested maps form JSON object从 JSON 对象读取嵌套地图时如何使用全局值
【发布时间】:2020-10-31 07:18:47
【问题描述】:

您好,我正在读取这样的 JSON 响应对象。

<td className="text-right flex">
     {finance.statuses.map((statuses) => {
     return statuses.currencyAmounts.map((amounts) => (
        <span className="pr-8" key={amounts.currencyId}>{amounts.maxGambleAmount}</span>
     ));
 })}
</td>

它运作良好,但我需要在每个值后面用索引 amounts.currencyId 绑定全局变量数组的货币缩写,我的问题是我无法访问内部映射中的货币。

我尝试了类似货币[amounts.currencyId],但没有成功。

有人可以帮助我吗?谢谢

【问题讨论】:

  • 您实际上是在寻找全球公开的“货币”,还是您可以在当前文件中import它?如果不需要全局可用,只需打开 currencies 定义所在的文件并确保正在导出变量(通过 export),然后您只需将其导入当前文件。 TS 文档:typescriptlang.org/docs/handbook/modules.html#import
  • 货币位于 mapStateToProps

标签: json reactjs typescript dictionary nested


【解决方案1】:

根据您的评论,您的 currencies 变量存在于您的 mapStateToProps 函数中。如果有mapStateToProps,您可能会使用redux 库。如果是这种情况,我强烈建议您花一些时间熟悉它。

但回到你的问题,通常mapStateToProps 会返回一个对象,并且该对象的所有属性都应该在组件的props 中可用。 如果您的 mapStateToProps 函数中已经有 currencies 可用,您可以简单地将其添加到 return 语句中,它会是这样的:

function mapStateToProps(state) {
    return {
        // this should make your "currencies" object/map available in the props of your component:
        currencies: state.currencies,
    };
}

// In your component you should have the "props" available as the parameter,
// you just have to access it now:
<td className="text-right flex">
     {finance.statuses.map((statuses) => {
     return statuses.currencyAmounts.map((amounts) => (
        <span className="pr-8" key={props.currencies[amounts.currencyId]}>{amounts.maxGambleAmount}</span>
     ));
 })}
</td>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多