Objects are not valid as a React child data from MongoDB

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

I'm working on a project that uses Flask as a backend and sends data from MongoDB database and sends it to React to print on the screen. In the Flash file

@app.route('/') @app.route('/post') def post(): db = connection.posthub cursor = db.post.find() //make the cursor  return render_template('index.html', cursor = cursor) //render template index.html with cursor 

In the pug file.

extends main  block content | {% for post in cursor %}  //Interating cursor with post variable #demo {{ post }} // sending post to demo for react to render |{% endfor %} 

In React file

import React from 'react'; import ReactDOM from 'react-dom';  class NewComponent extends React.Component {     constructor(props){     super(props);     this.state = {myData:{}}  }  componentDidMount(){     console.log("Mounting Components")     let data = document.getElementById('demo').InnerHTML; //getting data from html tag     console.log(typeof(data));     data = JSON.parse(data); // parse it     this.setState({myData:data}); //set the state  }  render(){     return(       <h3>{this.state.myData}</h3> //print it      );   } }   ReactDOM.render(     <NewComponent />,     document.getElementById('demo') ) 

It's printing:

{u'_id': ObjectId('597619b7c07b2dc30a108def'), u'description': u'hello', u'title': u'sankit'} {u'_id': ObjectId('59761b2cc6568a4e341b6b89'), u'description': u'lets add some thing new', u'title': u'hi'} 

In the console giving the error:

bundle.js:830 Uncaught Error: Objects are not valid as a React child (found:  object with keys {}). If you meant to render a collection of children, use  an array instead or wrap the object using createFragment(object) from the  React add-ons. Check the render method of `NewComponent`. 

and I was not able to print only the value of a specific key. need help

Edits: As suggested by @im_benton and @TW80000 I have some changes.

First I used bson_json_util.dumps while sending the cursor so that i'm sending a string not a list.

return render_template('index.html', cursor = dumps(cursor))  

Then in the pug file, I used window to create global variable and send the cursor to React

block content #demo script   | window.data = {{ cursor }}; 

Then in the React file, I tried to parse the string to JSON and render it iterating through it.

componentWillMount(){ console.log("Mounting Components"); let data = window.data; console.log(data); data = JSON.parse(data); console.log(data); this.setState({myData: data}); }  render() {     return this.state.myData.map(item => {         return (             <div>                 <h3>{item.title}</h3>                 <p>{item.description}</p>             </div>         );     }) } 

Still, i'm getting an empty array in console.log and if I don't use dumps an undefined object.

Mounting Components bundle.js:20844 Array(0) localhost/:1 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at NewComponent.componentWillMount (bundle.js:20845) at bundle.js:6685 at measureLifeCyclePerf (bundle.js:6412) at ReactCompositeComponentWrapper.performInitialMount ( 

Can you Help?

回答1:

You're getting that error because you're trying to render a plain object. This isn't allowed. You need to render a string, an element, or some other valid type.

I'm assuming that since you're using h3 tags you want to put the object's title in that spot. You could do something like

<h3>{this.state.myData.title}</h3> 

if myData is a single object (I can't quite tell from your code). If myData is an array of objects, you could do something like:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!