对象无法作为MongoDB的React子数据

时间:2017-08-22 21:51:11

标签: javascript json mongodb reactjs flask

我正在开发一个使用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

在帕格文件中。

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 个答案:

答案 0 :(得分:2)

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

我假设你因为你正在使用h3标签,你想把对象的标题放在那个位置。你可以做点什么

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

如果myData是一个单独的对象(我无法从你的代码中得知)。如果myData是一个对象数组,您可以执行以下操作:

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