【问题标题】:Objects are not valid as a React child - having to access to two children对象作为 React 孩子无效 - 必须访问两个孩子
【发布时间】:2021-11-05 21:47:58
【问题描述】:

我使用了 mongodb 的查找功能,我的输出包含两个对象。它通过 Postman 成功检索,但我无法在 react 应用上显示它。

这是从 monogodb 获取输出的后端代码。

  router.get("/employeepoints", (req, res) => {
  let empno = req.params.name;
  employees.aggregate([{ 
      $lookup: {
        from:"assignment_assignedtostaffs",
        localField:"empno",
        foreignField:"emp_no",
        as:"progress"
        }}  
      ])
    .exec((err, check) => {
      var l = check.length;
      return res.status(200).json({
        success: true,
        check: check,
        l: l,
      });
    });
});

邮递员的输出

{
   "success": true,
   "check": [
      {
         "_id": "6138f90bcf5f00948da795bb",
         "empno": 69,
         "name": "Nandasena",
         "progress":[
            {
               "_id": "6139a1336d16d204cc9b7504",
               "assignment_name": "Assignment2",
               "client_no": "clie3",
               "execid": "exec20",
               "place_of_engagement": "California",
               "distance": 4,
               "date_of_allocation": "2021-09-02T00:00:00.000Z",
               "deadline": "2021-09-18T00:00:00.000Z",
               "emp_no": 69,
               "progress": "Working",
               "__v": 0,
               "travel_allowance": 350
            }
         ]
      }
   ]
}

通过 React 获取上述输出。我可以访问检查中的元素,但不能访问进度。如上所示,如何访问正在进行的元素。

            <tbody class="tbody1">
              {this.state.employee.map((employees, index) => (
                <tr key={index}>
                  <td>
                    <a href={``} style={{ textDecoration: "none" }}>
                      {employees.empno}
                    </a>
                  </td>
                  <td>{employees.name}</td>
                  <td>{employees.email}</td>
                  <td>{employees.commencement_date}</td>
                  <td>{employees.progress.distance}</td>
                  <td>1</td>
                  <td>
}

【问题讨论】:

  • employess.progress 是一个数组。映射项目以访问数据。
  • 我如何循环遍历已经循环的数组?如果你能帮助我真的会很有帮助...尝试了所有可能的方法

标签: node.js reactjs mongodb


【解决方案1】:

您应该循环遍历employees.progress 数组,为数组中的每个项目返回一个新的td 单元格,并将id 用作key

...
<td>{employees.commencement_date}</td>
{employees.progress.map(item => (
    <td key={item.id}>
        {item.distance}
    </td>
))}
<td>1</td>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多