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

标签 javascript reactjs

我有两个列表我想动态更新,如果单击它会将数组中的项目移动到“存档”列表或“收藏夹”列表,我已经映射了存储在父组件状态中的每个列表但是我得到 x is undefined 的错误,所以我检查数组中是否有多个项目,但它随后使列表不可用并抛出每个列表未定义的错误,我不确定关于在没有任何初始项时如何正确呈现每个数组。代码如下

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: [],
    }
  }

最佳答案

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

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

但是你有这个结构:

var props = {
    favourites: []
}

所以favourites.results是未定义的,也就是说favourites.results.map等同于undefined.map,这是一个ReferenceError。

关于javascript - 如何在具有空数组的 React 组件中定义 .map 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50118507/

相关文章:

reactjs - 在 ag-Grid 中设置列​​的细宽度不起作用

javascript - 点击时 Fancybox 加载 div?

javascript - 解析时的额外值,然后循环遍历 JSON 字符串

javascript - 根据文本中出现的字符串填充数组

javascript - React 中的 state 和 props 有什么区别?

javascript - 排序 react native FlatList

reactjs - create-react-app 的缺点是什么?

javascript - 有没有办法将 JavaScript 函数从 src 文件夹外部导入到 React 组件

javascript - 如何使用 jenkins 部署 javascript 项目?

reactjs - 在 Redux 状态下存储配置对象