如何在具有空数组的React组件中定义.map列表?

时间:2018-05-01 14:39:46

标签: javascript reactjs

我有两个要动态更新的列表,如果点击它会将数组中的项目移动到'已存档'列表或最喜欢的' list,我已经映射了存储在父组件状态中的每个列表,但是我得到x的错误是未定义的,所以我检查一下该数组中是否有多个项目,但它然后生成列表&# 39; s不可用并抛出未定义的每个列表的错误,我不确定如何在没有任何初始项目的情况下正确渲染每个数组。代码如下:

import React from 'react'
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';

import PropertyCard from '../../card/Property/index'

import '../../../../../sass/includes/sidebar/Result/sidebar.scss'

const ResultsSideBar = (props) => {
  const favourites = props.favourites.results.map((result) =>
    <li className="fvt-List_Item">
      <PropertyCard
        key={result.id}
        title={result.title}
        price={result.price}
        beds={result.beds}
        bathrooms={result.bathrooms}/>
    </li>
  )

  const archived = props.archived.results.map((result) =>
    <li className="fvt-List_Item">
      <PropertyCard
        key={result.id}
        title={result.title}
        price={result.price}
        beds={result.beds}
        bathrooms={result.bathrooms}/>
    </li>
  )

  return (
    <Tabs className="rst-SideBar">
      <TabList className="rst-SideBar_Tabs">
        <Tab className="rst-SideBar_Tab">
          <p className="rst-SideBar_Text">0 Favourites</p>
        </Tab>
        <Tab className="rst-SideBar_Tab">
          <p className="rst-SideBar_Text">Archived</p>
        </Tab>
      </TabList>

      <TabPanel className="rst-SideBar_TabContent rst-SideBar_TabContent-favourites">
        <div className="fvt-List">
          <ul className="fvt-List_Items">
            {props.favourites.length ? {favourites} : <div>You have no favourites. </div>}
          </ul>
        </div>
      </TabPanel>

      <TabPanel className="rst-SideBar_TabContent rst-SideBar_TabContent-archived">
        <div className="fvt-List">
          <ul className="fvt-List_Items">
            {props.archived.length ? {archived} : <div>You have no archived items. </div>}
          </ul>
        </div>
      </TabPanel>
    </Tabs>
  )
}

export default ResultsSideBar

父组件状态供参考:

class Results extends React.Component{
  constructor(props) {
    super(props)

    this.state = {
      results: resultsData,
      favourites: [],
      archived: [],
    }
  }

1 个答案:

答案 0 :(得分:1)

您正在执行props.favourites.results.map,这将适用于此结构:

var props = {
    favourites: {
        results: []
    }
}

但你有这个结构:

var props = {
    favourites: []
}

所以favourites.results未定义,这意味着favourites.results.map等同于undefined.map,这是一个ReferenceError。