我的网站导航具有以下数据结构。这只是一个JSON对象:

[{
  "path": "/",
  "name": "Home"
}, {
  "path": "/products",
  "name": "Products",
  "subnav": [{
    "path": "/sharing-economy",
    "name": "Sharing Economy"
  }, {
    "path": "/pre-employment-screening",
    "name": "Pre-Employment Screening"
  }, {
    "path": "/kyc-and-aml",
    "name": "KYC & AML"
  }]
}, {
  "path": "/checks",
  "name": "Checks"
}, {
  "path": "/company",
  "name": "Company"
}]

我想做的是从中渲染以下内容,当存在Products键时,在subnav列表项中有一个嵌套列表:
<ul>
  <li>Home</li>
  <li>Products
    <ul>
      <li>Sharing Economy</li>
      <li>Pre-Employment Screening</li>
      <li>KYC & AML</li>
    </ul>
  </li>
  <li>Checks</li>
  <li>Company</li>
</ul>

目前,我的React代码如下所示:
// This is the data structure from above
import navigation from '../data/navigation.json'

const SubNavigation = (props) => {
  // Here I’m trying to return if the props are not present
  if(!props.subnav) return
  props.items.map((item, index) => {
    return <Link key={index} to={item.path}>{item.name}</Link>
  })
}

class Header extends React.Component {

  render() {
    return (
      <header className='header'>
        {navigation.map((item, index) => {
          return(
            <li key={index}>
              <Link to={item.path}>{item.name}</Link>
              <SubNavigation items={item.subnav}/>
            </li>
          )
        })}
      </header>
    )
  }
}

export default Header

我使用的是功能性的无状态组件来呈现SubNavigation,但是当item.subnavundefined时遇到麻烦。

我将如何修改此代码,以便根据存在/未定义的SubNavigation键有条件地呈现item.subnav

最佳答案

您可以尝试一下:

  <header className='header'>
    {navigation.map((item, index) => {
      return(
        <li key={index}>
          <Link to={item.path}>{item.name}</Link>
          { item.subnav && <SubNavigation items={item.subnav}/> }
        </li>
      )
    })}
  </header>

关于javascript - 在React中渲染嵌套导航,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35673679/

10-11 05:50