首页 > 解决方案 > 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;

标签: javascriptreactjsfrontend

解决方案


可以使用条件渲染来渲染您的位置。因此,如果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>

推荐阅读