您可能已经返回undefined,数组或其他一些无效对象呈现状态数据 [英] You may have returned undefined, an array or some other invalid object rendering state data

查看:176
本文介绍了您可能已经返回undefined,数组或其他一些无效对象呈现状态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React中迭代列表和打印元素时一直面临问题。

Have been facing issue while iterating through a list and printing elements in React.

反应代码是:

import React from 'react';
import ReactDOM from 'react-dom';

class NewComponent extends React.Component {
    constructor(props){
        super(props);
        this.state = {myData: []}
    }

    componentWillMount(){
        let data = document.getElementById('demo').innerHTML;
        data = JSON.parse(data);
        this.setState({myData: data});
    }

    render() {
        return this.state.myData.map((item) => {
        return (
            <div>
                <h3>{item.title}</h3>
                <p>{item.description}</p>
            </div>
            );
         });
       }
     }


ReactDOM.render(
    <NewComponent />,
    document.getElementById('demo')
 )

我收到的错误是:

bundle.js:830 Uncaught Error: NewComponent.render(): A valid React element 
(or null) must be returned. You may have returned undefined, an array or 
some other invalid object.

我很确定
的渲染函数中的返回存在问题不知道问题是什么。

I'm pretty sure there is some issue with returns in the render function of the Not sure what is the issue though.

编辑

我做了在编辑之后,错误不再存在,但没有任何东西在渲染。

I have made the following edits, the error is not there anymore but nothing is rendering.

renderList() {
console.log("Running");
return  this.state.myData.map((item) => {
    <div>
      <h3>{item.title}</h3>
      <p>{item.description}</p>
    </div>
  });
}

render() {
    console.log(this.state.myData);
    if(this.state.myData.length)
        return <div>{this.renderList()}</div>
    else
        return <div>Loading...</div>
 }

在Chrome控制台中我得到:

In Chrome console I'm getting:

(2) [{…}, {…}]
 0:{_id: {…}, description: "hello", title: "sankit"}
 1:{_id: {…}, description: "lets add some thing new", title: "hi"}
 length:2
 _proto_:Array(0)

 Running


推荐答案

你能做什么do是通过一个单独的方法从render方法中提取你的js代码,如下所示:

what you can do is extract your js code from the render method in a separate method like so:

renderList() {
   return this.state.myData.map((item) => {
      <div>
       <h3>{item.title}</h3>
       <p>{item.description}</p>
      </div>
   })
}

然后在你的渲染方法中:

then in your render method:

render() {
  if(this.state.myData.length){
    return (
       <div>{this.renderList()}</div>
    );
  }
  else
  {
    return (
      <div>Loading...</div>
    );
  }
}

这篇关于您可能已经返回undefined,数组或其他一些无效对象呈现状态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆