javascript - ReactJS:TypeError:无法读取未定义的属性“地图”
问题描述
我在提取地点数据的 ReactJS 应用程序中收到此错误。在我看来,错误显示何时map()
指向null
TypeError:无法读取未定义的属性“地图”
我想不出一种方法来设置默认值
这是代码:
import React, {Component} from 'react';
// This component is for search list view, it render the props places data,
// And handle cilck for place item.
class SearchList extends Component {
render() {
// const {places, query, selectPlace} = this.props;
const {places,query,selectPlace} = this.props;
return (
<div className="container">
<hr/>
<div className="input-group">
<input
type="text"
className="form-control"
placeholder="Filter"
aria-label="Filter Input"
onChange={(event) => {
query(event.target.value);
}}
/>
<span className="input-group-addon">
<i className="fas fa-filter"></i>
</span>
</div>
<hr/>
<div style={{maxHeight: '82vh', overflow: 'scroll'}}>
<ul className="list-group">
{
places.map(place => (
<li
tabIndex="0"
key={place.id}
className="list-group-item list-group-item-action"
onClick={() => selectPlace(place)}>
<span>{place.name}</span>
</li>
))
}
</ul>
</div>
</div>
);
}
}
export default SearchList;
解决方案
可以使用条件渲染来渲染您的位置。因此,如果places
未定义,则不会呈现与运算符 (&&) 的右操作数
<ul className="list-group">
{
places && places.map(place => (
<li
tabIndex="0"
key={place.id}
className="list-group-item list-group-item-action"
onClick={() => selectPlace(place)}>
<span>{place.name}</span>
</li>
))
}
</ul>
推荐阅读
- html - 在 React 中使用 button-onClick 事件而不是 input-onChange 事件来改变状态
- vue.js - 为什么 HappyPack 在 webpack4 和 vue-cli4 中抛出错误
- amazon-redshift - Redshift 中时间序列表的保留管理
- asp.net-core - Azure AD 集成到 IdentityServer4 详细教程
- spring-boot-admin - Spring Boot 管理员在自定义视图中重用 base css
- ffmpeg - Ffmpeg 和 ffprobe 未在 m3u8 文件中显示字幕流
- javascript - 用vue js异步提交表单后关闭引导模式5
- javascript - 对象数组:从对象中删除键并将它们作为新对象添加到同一数组中
- python - Python GUI 连接到 SQL Server 数据库
- java - 如何在本地机器上测试 Azure 托管标识连接?