【发布时间】:2021-06-17 07:27:25
【问题描述】:
我的 react 项目中有一个文件,glossaryItems.json。该文件如下所示:
{
"glossary": [
{
"name": "Constant",
"pageNumber": "33",
"definition": "A value that cannot change while the program is running.",
},
{
"name": "Debugging",
"pageNumber": "45",
"definition": "The process of finding and reducing the number of defects in a computer program.",
},
{
"name": "Algorithm",
"pageNumber": "4",
"definition": "A strictly defined finite sequence of well-defined statements that provides the solution to a problem."
}
]
}
我有另一个文件,glossaryPage.tsx,我想在其中显示选项卡中的每个词汇表项。我不确定如何访问 json 文件以便在 tsx 文件中使用它。我最终将 json 文件更改为 .ts 文件并将其导出:
export const glossaryItems =
[
{
"glossary": [
{
"name": "Constant",
"pageNumber": "33",
"definition": "A value that cannot change while the program is running.",
},
{
"name": "Debugging",
"pageNumber": "45",
"definition": "The process of finding and reducing the number of defects in a computer program.",
},
{
"name": "Algorithm",
"pageNumber": "4",
"definition": "A strictly defined finite sequence of well-defined statements that provides the solution to a problem."
}
]
}
]
然后将其导入到glossaryPage.tsx 中。我希望能够分别获取 json 的每个部分,以便能够在选项卡中使用它。因此,我将有一个标记为“常量”的选项卡,第二个选项卡,“调试”,第三个选项卡“算法”,并在每个选项卡下显示适用于该选项卡的页码和定义等信息。我尝试仅在词汇表上进行映射,但无法做到。我必须映射词汇表。
const GlossaryPage = () => {
const terms = glossaryItems.map(({glossary}, key) => (
<div key={key}>
{glossary.map(({name, pageNumber, definition}, key) => (
<div key={key}>
<p>{name}</p>
</div>
))}
</div>
))
return (
<SprkTabsPanel
isDefaultActive
tabBtnChildren={terms[0]} //this is where the terms are printing out on the tab
tabBtnAnalyticsString="tab-1"
tabBtnDataId="tab-1"
>
</SprkTabsPanel>
我认为通过对术语进行索引,它会给我该索引处的术语,但它给了我所有的术语。这是它的样子:
如何获取对象的各个值?
任何帮助将不胜感激!
【问题讨论】:
-
只要您的
tsconfig中有"resolveJsonModule": true,您就可以直接从.json文件导入。我得仔细看看为什么你的映射是错误的。
标签: arrays json reactjs typescript