反应嵌套的路由器javascript数组对象

时间:2018-07-10 22:35:35

标签: javascript arrays json reactjs react-router

我正在使用React Router 4,并试图从本质上单击指向某个组件的链接,然后让它呈现链接到该特定组件的文章。

我可以将其转换为component1

const sectionType = Items[sectionNumber].key;
console.log(sectionType);

// this logs out component1 or component2

然后我无法从JSON获取文章名称:

这会注销正确的答案:

console.log(articles.component1[0].articleTitle);

但这不是:

console.log(articles.sectionType[0].articleTitle);

sections.js:34 Uncaught TypeError: Cannot read property '0' of undefined

基本上,在使用React Router时,如何传递sectionType以获取正确的文章。

路由

{["/component1/", "/component2/"].map((path, index) => (
  <Route
    path={path}
    key={index}
    render={props => (
      <Sections
        {...props}
        sectionNumber={index}
        Items={Items}
        articles={articles}
      />
    )}
  />
))}

文章JSON

{
  "component1": [
    {
      "index": 0,
      "balance": "$2,384.34",
      "articleTitle": "do dolore do ex culpa velit",
      "article":
        "qui ullamco sunt in id laboris"
    },
    {
      "index": 1,
      "balance": "$2,525.44",
      "articleTitle": "occaecat cillum ad occaecat aliqua est",
      "article":
        "aliquip ad cupidatat commodo reprehenderi"
    }
  ],
  "component2": [
    {
      "index": 0,
      "balance": "$2,384.34",
      "articleTitle": "do dolore do ex culpa velit",
      "article":
        "qui ullamco sunt in id laboris"
    },
    {
      "index": 1,
      "balance": "$2,525.44",
      "articleTitle": "occaecat cillum ad occaecat aliqua est",
      "article":
        "aliquip ad cupidatat commodo reprehenderi"
    }
  ]
}

ITEMS JSON

[
  {
    "content": "Component1",
    "key": "component1",
    "to": "/component1"
  },
  {
    "content": "Component2",
    "key": "component2",
    "to": "/component2"
  }
]

0 个答案:

没有答案