Promise Error: Objects are not valid as a React child

前端 未结 2 908
清酒与你
清酒与你 2020-12-09 08:17

I am trying to set the json to a state using user agent, I get the error:

Uncaught Invariant Violation: Objects are not valid as a React child (found:

相关标签:
2条回答
  • 2020-12-09 08:22

    You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

    I am pasting a link from where you can learn how to render elements from an array with React.

    http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

    Hope it helps!

    0 讨论(0)
  • 2020-12-09 08:29

    You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

    render: function() {
      return (
        <span>
          // This will go through all the elements in arrayFromJson and
          // render each one as a <SomeComponent /> with data from the object
          {this.state.arrayFromJson.map(function(object) {
            return (
              <SomeComponent key={object.id} data={object} />
            );
          })}
        </span>
      );
    }
    
    0 讨论(0)
提交回复
热议问题