【发布时间】: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