我正在开发一个项目,该项目使用 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 中得到一个空数组,如果我不使用 dumps 一个 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 (
你能帮忙吗?
最佳答案
您收到该错误是因为您正在尝试渲染一个普通对象。这是不允许的。您需要呈现字符串、元素或其他一些有效类型。
我假设由于您使用的是 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>
);
})
}
}
关于javascript - 对象作为来自 MongoDB 的 React 子数据无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45827542/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa
我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的rubyyaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir