无法读取未定义的TypeError属性“ map”

时间:2019-02-19 16:51:04

标签: reactjs leaflet react-leaflet

我正在尝试让我的React Map应用程序引用我的mongodb的另一个集合。会话功能可以很好地显示标记,但是当我尝试同时显示它们时,会发生错误。我正在尝试使用与显示DB的另一个集合中的数据相同的格式:

         {this.state.Sessions.map(UsersSession => (
           <Marker
                   position={[UsersSession.latitude, UsersSession.longitude]}
                   icon={myIcon} >
              <Popup>
              <em>{UsersSession.event}, </em>
                  {UsersSession.venue} {'\n'}

                  <Button color="primary" size="sm">More info</Button>
                  <Chart/>
              </Popup>
           </Marker>
         ))}

         {this.state.members.map(Users => (
           <Marker
                   position={[Users.location.latitude, Users.location.longitude]}
                   icon={myIcon} >
              <Popup>
              <em>{Users.name}, </em>
                  {Users.bio} {'\n'}

                  <Button color="primary" size="sm">More info</Button>
                  <Chart/>
              </Popup>
           </Marker>
         ))}
       </Map>

这导致以下错误:

  

TypeError:无法读取未定义的属性“ map”

即使我定义了我的className。可能与我的架构有关吗?还是我的JSX代码中的问题。

我的members.js文件(服务器端):

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

const express = require('express');
const Joi = require("joi");

const db = require('../db');
const members = db.get('members');

//Defining the schema for the backend.
const schema1 = Joi.object().keys({
    name:   Joi.string().min(1).max(100).required(),
    bio:   Joi.string().min(1).max(500).required(),
    latitude:    Joi.number().required(),
    longitude:   Joi.number().required()
});

const router = express.Router();

//Gets all sessions that are found within the DB.
router.get('/', (req, res) => {
  members
  .find()
  .then(allmembers =>{
      res.json(all);
    });
});
//POST for when no errors are produced.
router.post('/', (req, res, next) => {
  const result = Joi.validate(req.body, schema);
  if (result.error == null) {
//Removes the need to write eg) req.body.name below.
    const {name,bio, latitude, longitude,} = req.body;
    const members = {
      name,
      bio,
      latitude,
      longitude,
      date: new Date()
     };
   members.insert(members).then(insertedMessage => {
         res.json(insertedMessage);
   });
 }
else {
  next(result.error);
   }
});

module.exports = router;

2 个答案:

答案 0 :(得分:3)

您还可以仅在存在会话或成员时运行地图功能。为此,您可以在下面进行检查,例如:

{this.state.Sessions && this.state.Sessions.map(UsersSession ....... rest of the logic}

答案 1 :(得分:2)

在完成网络请求之前,您很可能没有Sessionsmembers阵列。您可以添加空数组的默认值来解决此问题。

class App extends React.Component {
  state = {
    Sessions: [],
    members: []
  };

  // ...
}