繁体   English   中英

React App 无法读取未定义的属性“地图”

[英]React App cannot read property 'map' of undefined

我是 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: import { Categories, Sorting, Item } from '../index'

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

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

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

尝试

console.log(this.props.items) 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM