我提前道歉,我是一个 JS/ReactJS 新手,我在表述这个问题时遇到了麻烦,所以如果这已经在某处得到了回答,我很抱歉。
我有一个这样的对象:
Object {Joy: 0.719115, Extraversion: 0.59527, Agreeableness: 0.650457}
我希望能够为对象中的所有键返回 html。截至目前,它只返回第一个键的 html(显然,如果我没记错的话,返回会中断循环)。如何实现对象中所有键的 html 渲染?
import React from 'react'
export const MessageSentiment = (props) => {
var sentiment = JSON.parse(props.sentiment)
console.log(sentiment)
for(var key in sentiment ) {
console.log(key, sentiment[key])
return (<h1>{key}: {sentiment[key]*100}</h1>)
}
}
这些是输出和所需的输出
Output:
<h1>Joy: 71.9115</h1>
Expected output:
<h1>Joy: 71.9115</h1>
<h1>Extraversion: 59.527</h1>
<h1>Agreeableness: 65.0456</h1>
不确定这是否与此有关,但我在控制台中收到警告:
../src/components/messages/MessageSentiment.js
6:5 warning The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype guard-for-in
✖ 1 problem (0 errors, 1 warning)
printWarnings @ webpackHotDevClient.js:196
handleWarnings @ webpackHotDevClient.js:209
connection.onmessage @ webpackHotDevClient.js:255
EventTarget.dispatchEvent @ eventtarget.js:49
(anonymous) @ main.js:274
SockJS._transportMessage @ main.js:272
EventEmitter.emit @ emitter.js:44
WebSocketTransport.ws.onmessage @ websocket.js:35