【问题标题】:Getting error while putting an array onto state - React将数组置于状态时出错 - React
【发布时间】:2020-09-28 01:58:09
【问题描述】:

我正在从运行 MongoDB 的 Express 后端接收一个数组,目前正在使用 .toArray() 函数检索一个数组,后端一切正常。

所以问题是当我在前端接收数组时,我试图用 setState 函数将它传递给状态,它给了我这个错误

错误:对象作为 React 子项无效(发现:对象带有键 {_id、uploaderId、uploaderName、title、subtitle、description、language、category、subcategory、currency、price、contents、likes、dislikes、coverImage、封面视频})。如果您打算渲染一组子项,请改用数组。

Here's an image of the object structure (the courses property is the one that has the retrieved array from the back-end)

实际的代码是这样的

axios({
                url: "/course/data",
                method: "GET",
                params: {id: userInfo._id},
            }).then(response => {
                userInfo.courses = response.data;
                console.log(userInfo);
                this.setState(userInfo);
            }).catch(err => err ? alert(err) : null);

【问题讨论】:

  • 错误信息告诉你出了什么问题!你的反应组件应该返回有效的 HTML 标记,或者 null。什么是前面提到的组件返回?
  • 哦,谢谢,我没有注意到,但我忘记删除代码中的某处有 {this.state.courses}。我删除了它,现在很好!非常感谢@Frosty619
  • 乐于助人!您可以点赞评论以表达您的感激之情:D
  • 直到现在我都不知道你可以投票给 cmets。再次感谢!

标签: javascript arrays reactjs mongodb api


【解决方案1】:

我的代码中有一个 {this.state.courses} 隐藏在本应为 {this.state.courses.length} 的位置,因此删除它可以解决问题,就像 @Frosty619 所说的那样。

【讨论】:

    【解决方案2】:

    试试这个,

    axios({
        url: "/course/data",
        method: "GET",
        params: {id: userInfo._id},
    }).then(response => {
         userInfo["courses"] = response.data.courses;
         this.setState({userInfo:userInfo});
    
    
    }).catch(err => err ? alert(err) : null);
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      相关资源
      最近更新 更多