对象不适合作为来自MongoDB的React子数据 [英] Objects are not valid as a React child data from MongoDB
问题描述
我正在开发一个使用Flask作为后端的项目,并从MongoDB数据库发送数据并将其发送到React以在屏幕上进行打印。
在Flash文件中
@ app.route('/')
@ app.route '/ post')
def post():
db = connection.posthub
cursor = db.post.find()//使游标
返回render_template('index .html',cursor = cursor)//渲染模板index.html与游标
在pug文件
扩展主
块内容
| {%for cursor in cursor%} //将游标与帖子变量进行交互
#demo {{post}} //发送帖子给演示用于渲染
| {%endfor%}
在React文件中
导入从反应中反应;
从'react-dom'导入ReactDOM;
$ b $ class NewComponent extends React.Component {
constructor(props){
super(props);
this.state = {myData:{}}
}
componentDidMount(){
console.log(挂载组件)
let data = document.getElementById('demo')。InnerHTML; //从html标签获取数据
console.log(typeof(data));
data = JSON.parse(data); //解析它
this.setState({myData:data}); //设置状态
}
render(){
return(
< h3> {this.state.myData}< / h3> //打印
);
$ b ReactDOM.render(
< NewComponent /> ;,
document.getElementById('demo')
$ / code>
正在打印:
{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'}
在控制台发出错误信息:
bundle.js:830 Uncaught错误:对象作为React子项无效(找到:带键{
的对象})。如果您打算渲染一个子集合,请改为使用
数组,或者使用
React附加组件中的createFragment(object)封装对象。检查NewComponent的渲染方法。
我无法仅打印特定键的值。
需要帮助
编辑:
正如@im_benton和@ TW80000所建议的,我有一些改变。
首先,我在发送游标时使用了bson_json_util.dumps,以便发送一个不是列表的字符串。
return render_template('index.html',cursor = dumps(cursor))
然后在帕格文件,我用窗口来创建全局变量,并将光标发送到React
块内容
#demo
脚本
| window.data = {{cursor}};
然后在React文件中,我尝试将字符串解析为JSON并使其迭代。
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>
);
})
}
console.log,如果我不使用转储一个未定义的对象。
$ b $ pre $ 安装组件
bundle.js:20844 Array(0)
localhost /:1未捕获SyntaxError:JSON输入意外结束$ b $ J at JSON.parse(< anonymous>)
at NewComponent.componentWillMount(bundle.js:20845)
at bundle.js:6685
at measureLifeCyclePerf(bundle.js:6412)
at ReactCompositeComponentWrapper.performInitialMount(
您可以帮忙吗?
渲染一个普通的对象你需要呈现一个字符串,一个元素,或其他有效的类型。
我假设,因为你正在使用你想要的h3标签把对象的标题放在那个地方。您可以做一些类似于
< h3> {this.state.myData.title}< / h3>
如果 myData
是单个对象(I不能从你的代码中看出来)。如果 myData
是一个对象数组,则可以这样做:
render(){
return this.state.myData.map(item => {
return(
< div key = {item._id}>
< ; h3> {item.title}< / h3>
< p> {item.description}< / p>
< / div>
);
})
}
}
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?
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>
);
})
}
}
这篇关于对象不适合作为来自MongoDB的React子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!