Promise 错误:对象作为 React 子对象无效 [英] Promise Error: Objects are not valid as a React child
问题描述
我正在尝试使用用户代理将 json 设置为某种状态,但出现错误:
I am trying to set the json to a state using user agent, I get the error:
Uncaught Invariant Violation:对象作为 React 子对象无效(发现:对象带有键 {...}).如果您打算渲染一组子项,请改用数组或使用 React 附加组件中的 createFragment(object) 包装对象.
Uncaught Invariant Violation: 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.
设置状态的方法:
getInitialState: function(){
return {
arrayFromJson: []
}
},
loadAssessmentContacts: function() {
var callback = function(data) {
this.setState({arrayFromJson: data.schools})
}.bind(this);
service.getSchools(callback);
},
componentWillMount: function(){
this.loadAssessmentContacts();
},
onTableUpdate: function(data){
console.log(data);
},
render: function() {
return (
<span>{this.state.arrayFromJson}</span>
);
}
服务
getSchools : function (callback) {
var url = 'file.json';
request
.get(url)
.set('Accept', 'application/json')
.end(function (err, res) {
if (res && res.ok) {
var data = res.body;
callback(data);
} else {
console.warn('Failed to load.');
}
});
}
杰森
{
"schools": [
{
"id": 4281,
"name": "t",
"dfe": "t",
"la": 227,
"telephone": "t",
"address": "t",
"address2": "t",
"address3": "t",
"postCode": "t",
"county": "t",
"ofsted": "t",
"students": 2,
"activeStudents": 2,
"inActiveStudents": 0,
"lastUpdatedInDays": 0,
"deInstalled": false,
"inLa": false,
"status": "unnassigned",
"authCode": "t",
"studentsActivity": 0
},......
]}
推荐答案
你不能这样做:{this.state.arrayFromJson}
因为你的错误表明你试图做的不是有效的.您正在尝试将整个数组呈现为 React 子项.这是无效的.您应该遍历数组并呈现每个元素.我使用 .map
来做到这一点.
You can't do this: {this.state.arrayFromJson}
As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map
to do that.
我正在粘贴一个链接,您可以从中学习如何使用 React 渲染数组中的元素.
I am pasting a link from where you can learn how to render elements from an array with React.
http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/
希望有帮助!
这篇关于Promise 错误:对象作为 React 子对象无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!