【问题标题】:Objects are not valid as a React child data from MongoDB对象作为来自 MongoDB 的 React 子数据无效
【发布时间】:2017-08-22 21:51:11
【问题描述】:

我正在开发一个项目,该项目使用 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 %}

在反应文件中

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 (

你能帮忙吗?

【问题讨论】:

  • 从 html 标签中获取数据似乎是个糟糕的主意。
  • 至少可以将光标设置为窗口对象吗?然后你可能应该将其水合到减速器中,但首先将其设置为窗口。
  • 像这样在你的 pug 文件 ```` 脚本中。 window.data="#{光标}"; ``` 然后在你的反应组件中 ``` this.setState({myData: window.data}); //设置状态```
  • @im_benton 是的,我知道从 HTML 标签获取数据很糟糕,感谢您的想法,感谢。我已经对代码进行了更改,但仍然出现一些错误,请您帮我解决一下

标签: javascript json mongodb reactjs flask


【解决方案1】:

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

我假设由于您使用的是 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>
        );
    })
  }
}

【讨论】:

  • 感谢您的帮助,我最初使用的是单个对象,但您的想法似乎更有帮助。所以我使用了你和@im_benton 的想法并做了一些改变。虽然仍然有一些错误。你能帮帮我吗
  • 你最好的办法是用你的新问题打开一个新问题。如果你在评论中标记我,我可以看看它。
  • 我提出了一个新问题,听取您的建议,它工作正常,但列表迭代有问题。你能帮我吗?这是链接 - stackoverflow.com/questions/45908668/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 2018-05-27
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多