【问题标题】:React App cannot read property 'map' of undefinedReact App 无法读取未定义的属性“地图”
【发布时间】:2020-07-16 11:22:43
【问题描述】:

我是 ReactJS 的新手。我正在创建一个从 json 文件数据中获取并存储在公共文件夹中的应用程序。

class App extends React.Component {
  componentDidMount() {
    axios.get('http://localhost:3000/pizza.json').then(data => {
      store.dispatch(setPizza(data.Pizza))
    })
  }

  <Route path="/"     render    = { () => <Main items={ this.props.items }/>} exact></Route>

还有路由,我想在主页上显示组件。 所以,我有 Item 组件:

function Item({ image, name, types, sizes, price }) {
  const availableTypes = ['0', '1'];
  const availableSizes = [26, 30, 40];

  const [activeType, setActiveType] = useState(types[0])
  const [activeSize, setActiveSize] = useState(sizes[0])

  const onSelectType = index => {
    setActiveType(index)
  }

  const onSelectSize = index => {
    setActiveSize(index)
  }

  return (
    <div className="item">
      <img src={ image } alt="pizza1" className="item-preview"/>
      <h3 className="item-name">{ name }</h3>
      <div className="item-dimantion">
        <ul className="list">
        {
          availableTypes.map((type, index) => (
          <li
            key={type}
            className={classNames({
              choice: true,
              active: activeType === index ? 'active' : '',
              disable: types.includes(index)
            })}
            onClick={() => onSelectType(index)}>
            { type }
          </li>
        ))}
        </ul>

        <ul className="list">
          {
            availableSizes.map((size, index) => (
              <li key={ size }
                  className={classNames({
                    choice: true,
                    active: activeSize === index ? 'active' : '',
                    disable: sizes.includes(index)
                  })}
                  onClick={() => onSelectSize(index)}>
                  { size } см.
              </li>
            ))
          }
        </ul>
      </div>

      <div className="more">
        <h4 className="price">от { price }</h4>
        <button className="add">Добавить</button>
      </div>
    </div>
  )
}

然后,我在 Main 中调用 Item-component: 从 '../index' 导入 { Categories, Sorting, Item }

function Main({ items }) {
...
 <div className="main__content__items">
     {
        items.map(obj => {
           return (
              <Item key={obj}></Item>
           )
        })
      }
 </div>

这里我有问题(TypeError:无法读取未定义的属性'map'),很长时间无法修复......你能解释一下如何解决它吗?!谢谢!!!!

【问题讨论】:

  • 检查this.props.items 是否是一个数组。您可以在获取数据时传递this.props.items || [] 以避免该错误

标签: javascript json reactjs undefined


【解决方案1】:

您发布的所有代码看起来都是正确的。也许,您没有为 items 变量赋值。

试试

console.log(this.props.items) 

检查项目是否正确分配。如果未定义,请使用空数组。

【讨论】:

  • 是的,它是无敌的。但是,我必须在哪里初始化一个空数组?
  • this.props.items || [ ] ,同时通过它。
猜你喜欢
  • 2019-03-14
  • 2020-02-10
  • 2021-04-16
  • 2017-03-26
  • 2021-09-09
  • 2017-02-21
  • 2020-09-16
  • 2020-03-09
  • 1970-01-01
相关资源
最近更新 更多