不变违规:对象作为React子对象无效 [英] Invariant Violation: Objects are not valid as a React child
问题描述
在我的组件的渲染功能中,我有:
In my component's render function I have:
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>
);
}
一切都很好,但是当点击< li>
元素我收到以下错误:
everything renders fine, however when clicking the <li>
element I receive the following error:
未捕获错误:不变违规:对象无效React
child(找到:带键的对象{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附加组件中的createFragment(object)包装对象。检查欢迎
的渲染方法。
如果我改为 this.onItemClick.bind(this,item)
to (e)=> onItemClick(e,item)
在map函数中,一切都按预期工作。
If I change to this.onItemClick.bind(this, item)
to (e) => onItemClick(e, item)
inside the map function everything works as expected.
如果有人可以解释我做错了什么并解释为什么我得到这个错误,会很好
If someone could explain what I am doing wrong and explain why do I get this error, would be great
UPDATE 1:
onItemClick函数如下所示,删除this.setState会导致错误消失。
UPDATE 1:
onItemClick function is as follows and removing this.setState results in error disappearing.
onItemClick(e, item) {
this.setState({
lang: item,
});
}
但我无法删除此行,因为我需要更新此组件的状态
But I cannot remove this line as I need to update state of this component
推荐答案
我遇到了这个错误,结果发现我无意中在我的JSX代码中包含了一个我预期的对象成为字符串值:
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:
return (
<BreadcrumbItem href={routeString}>
{breadcrumbElement}
</BreadcrumbItem>
)
breadcrumbElement
曾经是一个字符串,但由于重构已成为一个Object。不幸的是,React的错误信息并没有很好地指出我存在问题的那一行。我必须一直跟着我的堆栈跟踪,直到我认识到传递给组件的道具然后我找到了有问题的代码。
breadcrumbElement
used to be a string but due to a refactor had become an Object. Unfortunately, React's error message didn't do a good job in pointing me to the line where the problem existed. 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.
你会需要引用作为字符串值的对象的属性,或者将Object转换为所需的字符串表示。如果您确实想要查看对象的内容,则一个选项可能是 JSON.stringify
。
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. One option might be JSON.stringify
if you actually want to see the contents of the Object.
这篇关于不变违规:对象作为React子对象无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!