本文翻译自:Invariant Violation: Objects are not valid as a React child
In my component's render function I have: 在组件的render函数中,我有:
render() {
const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
});
return (
<div>
...
<ul>
{items}
</ul>
...
</div>
);
}
everything renders fine, however when clicking the <li>
element I receive the following error: 一切正常,但是单击<li>
元素时,出现以下错误:
Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, dispatchMarker, nativeEvent, target, currentTarget, type, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchIDs}). 未捕获的错误:始终违反:对象作为React子对象无效(找到:带有键{dispatchConfig,dispatchMarker,nativeEvent,target,currentTarget,type,eventPhase,气泡,cancelable,timeStamp,defaultPrevented,isTrusted,视图,详细信息,screenX的对象,screenY,clientX,clientY,ctrlKey,shiftKey,altKey,metaKey,getModifierState,按钮,按钮,relatedTarget,pageX,pageY,isDefaultPrevented,isPropagationStopped,_dispatchListeners,_dispatchIDs})。 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. 如果您打算渲染孩子的集合,请改用数组或使用React附加组件中的createFragment(object)包装对象。 Check the render method of
Welcome
. 检查Welcome
的渲染方法。
If I change to this.onItemClick.bind(this, item)
to (e) => onItemClick(e, item)
inside the map function everything works as expected. 如果我将map函数内的this.onItemClick.bind(this, item)
更改为(e) => onItemClick(e, item)
,一切都会按预期进行。
If someone could explain what I am doing wrong and explain why do I get this error, would be great 如果有人可以解释我在做什么错并解释为什么我会收到此错误,那将是很好的
UPDATE 1: 更新1:
onItemClick function is as follows and removing this.setState results in error disappearing. onItemClick函数如下,删除this.setState导致错误消失。
onItemClick(e, item) {
this.setState({
lang: item,
});
}
But I cannot remove this line as I need to update state of this component 但是我无法删除此行,因为我需要更新此组件的状态
#1楼
参考:https://stackoom.com/question/2eXmp/不变违规-对象作为React子元素无效
#2楼
I was having this error and it turned out to be that I was unintentionally including an Object in my JSX code that I had expected to be a string value: 我遇到了这个错误,结果是我无意中在我的JSX代码中包含了一个我期望是字符串值的对象:
return (
<BreadcrumbItem href={routeString}>
{breadcrumbElement}
</BreadcrumbItem>
)
breadcrumbElement
used to be a string but due to a refactor had become an Object. breadcrumbElement
曾经是一个字符串,但是由于重构而成为对象。 Unfortunately, React's error message didn't do a good job in pointing me to the line where the problem existed. 不幸的是,React的错误消息不能很好地指出问题所在。 I had to follow my stack trace all the way back up until I recognized the "props" being passed into a component and then I found the offending code. 我必须一直跟踪堆栈跟踪,直到我意识到“ props”已传递到组件中,然后才发现有问题的代码。
You'll need to either reference a property of the object that is a string value or convert the Object to a string representation that is desirable. 您将需要引用对象的属性(它是字符串值),或者将Object转换为所需的字符串表示形式。 One option might be JSON.stringify
if you actually want to see the contents of the Object. 如果您确实想查看Object的内容,则一个选项可能是JSON.stringify
。
#3楼
So I got this error when trying to display the createdAt
property which is a Date object. 因此,当尝试显示createdAt
对象为Date对象时出现了此错误。 If you concatenate .toString()
on the end like this, it will do the conversion and eliminate the error. 如果像这样在最后连接.toString()
,它将进行转换并消除错误。 Just posting this as a possible answer in case anyone else ran into the same problem: 只是将其作为可能的答案发布,以防其他人遇到相同的问题:
{this.props.task.createdAt.toString()}
#4楼
I just got the same error but due to a different mistake: I used double braces like: 我只是遇到了相同的错误,但是由于一个不同的错误:我使用了像这样的双括号:
{{count}}
to insert the value of count
instead of the correct: 插入count
的值而不是正确的值:
{count}
which the compiler presumably turned into {{count: count}}
, ie trying to insert an Object as a React child. 编译器大概变成了{{count: count}}
,即试图插入一个对象作为React子对象。
#5楼
Just thought I would add to this as I had the same problem today, turns out that it was because I was returning just the function, when I wrapped it in a <div>
tag it started working, as below 只是以为我会加上这个问题,因为今天我遇到了同样的问题,结果是因为我只返回了函数,所以当我将其包装在<div>
标记中时,它开始工作,如下所示
renderGallery() {
const gallerySection = galleries.map((gallery, i) => {
return (
<div>
...
</div>
);
});
return (
{gallerySection}
);
}
The above caused the error. 以上导致错误。 I fixed the problem by changing the return()
section to: 我将return()
部分更改为:
return (
<div>
{gallerySection}
</div>
);
...or simply: ...或简单地说:
return gallerySection
#6楼
You were just using the keys of object, instead of the whole object! 您只是在使用对象的键,而不是整个对象!
More details can be found here: https://github.com/gildata/RAIO/issues/48 可以在这里找到更多详细信息: https : //github.com/gildata/RAIO/issues/48
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class SCT extends Component { constructor(props, context) { super(props, context); this.state = { data: this.props.data, new_data: {} }; } componentDidMount() { let new_data = this.state.data; console.log(`new_data`, new_data); this.setState( { new_data: Object.assign({}, new_data) } ) } render() { return ( <div> this.state.data = {JSON.stringify(this.state.data)} <hr/> <div style={{color: 'red'}}> {this.state.new_data.name}<br /> {this.state.new_data.description}<br /> {this.state.new_data.dependtables}<br /> </div> </div> ); } } SCT.propTypes = { test: PropTypes.string, data: PropTypes.object.isRequired }; export {SCT}; export default SCT;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>