reactjs - valid React element (or null) must be returned

后端 未结 1 1094
孤独总比滥情好
孤独总比滥情好 2021-02-10 18:23

I have the following simple code :

var data = [{ email: \"bob@gmail.com\" },{ email: \"toto@gmail.com\" }];
var User = React.createClass({
render: function ()
{
         


        
1条回答
  •  死守一世寂寞
    2021-02-10 18:46

    Here, the problem is in this line.

    return
    (
        
  • {this.props.email}
  • );

    You have put the starting parentheses on the next line so when your code is converted into plain javascript code, it will look something like this.

    render: function () {
        return; // A semicolon has been inserted.
        (React.createElement("li", null, this.props.email)); // unreachable code
    }
    

    You can see that a semicolon has been inserted by Javascript while interpreting your code, so no value is returned from the render function and you are getting this error.

    To avoid this situation, you need to put the starting parentheses after the return statement, so that Javascript won't insert a semicolon until a matching ending parentheses is found. Like this,

    return (
         
  • {this.props.email}
  • );

    Now if you look at the generated code, it will look something like this

    render: function () {
        return (React.createElement("li", null, this.props.email));
    }
    

    Also, change

    return
    (
       
      {userNodes}
    );

    to

    return (
        
      {userNodes}
    );

    Here, is the working fiddle. JSFiddle

    I have also fixed the warning,

    Each child in an array or iterator should have a unique "key" prop.

    by passing key in your User component.

    0 讨论(0)
提交回复
热议问题