[英]How to fix error objects are not valid react child?
I am trying map through an object with the goal to render the key and their value inside ap tag.我正在尝试通过一个对象映射,目的是在 ap 标记内呈现键及其值。 I am having the error message object are not valid react child.
我有错误消息对象是无效的反应子。
How can I overcome this error?我该如何克服这个错误?
<div className="d-flex flex-wrap">
{
Object.keys(features).map((item,index) => {
console.log('type',item);
console.log(features[item]);
return <p key={item} className="fw-bold bg-light fs-6 text-primary m-1 p-2">{{[item]:features[item]}}</p>
})
}
</div>
This error is because the code这个错误是因为代码
{{[item]:features[item]}}
actually results to an object.实际上结果是一个对象。 So child of
<p>
tag is an object.所以
<p>
标签的子元素是一个对象。 You can solve it by using Template literals inside <p>
tag您可以通过在
<p>
标记中使用模板文字来解决它
<div className="d-flex flex-wrap">
{
Object.keys(features).map((item,index) => {
console.log({[item]:features[item]});
console.log(features[item]);
return <p key={item} className="fw-bold bg-light fs-6 text-primary m-1 p-2" >{`{${item}: ${features[item]}}`}</p>
})
}
</div>
In this section of React doc , it is said that:在 React doc的这一部分中,据说:
You can put any valid JavaScript expression inside the curly braces in JSX
您可以将任何有效的 JavaScript 表达式放在 JSX 中的花括号内
Moreover {[item]:features[item]}
itself is not a valid expression, according to this list此外,根据此列表,
{[item]:features[item]}
本身不是有效的表达式
So instead, you have to embed 2 expressions, item
and features[item]
因此,您必须嵌入 2 个表达式,
item
和features[item]
return (
<p key={item} className="fw-bold bg-light fs-6 text-primary m-1 p-2">
{item}: {features[item]}
</p>
)
It is because of the double brackets in your code这是因为您的代码中的双括号
Use only one brackets like this像这样只使用一个括号
{[item]:features[item]}
Following is JSON以下是JSON
{[item]:features[item]}
If you meant to render the JSON as a string then do like this.如果您打算将 JSON 呈现为字符串,请这样做。
JSON.stringify({[item]:features[item]})
Do it like this像这样做
Object.keys(features).map((item) => {
return <p> {item} : {features[item]}</p>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.