对象作为来自 MongoDB 的 React 子数据无效

IT技术 javascript json mongodb reactjs flask
2021-05-14 01:51:54

我正在开发一个项目,该项目使用 Flask 作为后端并从 MongoDB 数据库发送数据并将其发送到 React 以在屏幕上打印。在 Flash 文件中

@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

在 pug 文件中。

extends main

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

在react文件中

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')
)

它正在打印:

{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 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`.

而且我无法仅打印特定键的值。需要帮忙

编辑:正如@im_benton 和@TW80000 所建议的,我有一些变化。

首先,我在发送游标时使用了 bson_json_util.dumps,因此我发送的是字符串而不是列表。

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

然后在 pug 文件中,我使用 window 创建全局变量并将光标发送到 React

block content
#demo
script
  | 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 中得到一个空数组,如果我不使用转储一个未定义的对象。

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 (

你能帮我吗?

1个回答

您收到该错误是因为您正在尝试渲染一个普通对象。这是不允许的。您需要呈现字符串、元素或其他一些有效类型。

我假设由于您使用的是 h3 标签,因此您希望将对象的标题放在该位置。你可以做类似的事情

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

ifmyData是单个对象(我无法从您的代码中完全分辨出来)。如果myData是一个对象数组,您可以执行以下操作:

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