React js 遍历 jsx 中的对象
react js iterating through an object in jsx
React.js 中的这段代码需要显示一个简单的 table,单元格由 db.json 中的数据填充,但我唯一看到的是空白页,我试图 console.log(cell)
在 td
中并记录了正确的信息,但屏幕上没有显示任何内容。
Sheet.js
import React from 'react'
function Sheet() {
const data = require('../store/db.json')
const mySheet = data.sheet1
return (
<>
<table>
<tbody>
{
Object.entries(mySheet).forEach(([row, cols]) => (
<tr key={row}>
{
Object.entries(cols).forEach(([col, cell]) => (
<td key={`${row},${col}`}>
{cell}
</td>
))
}
</tr>
))
}
</tbody>
</table>
</>
)
}
export default Sheet
db.json
{
"sheet1": {
"1": {
"1": "1,1",
"2": "1,2",
"3": "1,3"
},
"2": {
"1": "2,1",
"2": "2,2",
"3": "2,3"
},
"3": {
"1": "3,1",
"2": "3,2",
"3": "3,3"
}
}
}
.forEach
JS数组方法总是returns undefined
.
console.log([1, 2, 3].forEach(x => x * 2)) // -> undefined
如果您想 return 来自源数组的另一个数组,请使用 .map
console.log([1, 2, 3].map(x => x * 2)) // [2, 4, 6]
React.js 中的这段代码需要显示一个简单的 table,单元格由 db.json 中的数据填充,但我唯一看到的是空白页,我试图 console.log(cell)
在 td
中并记录了正确的信息,但屏幕上没有显示任何内容。
Sheet.js
import React from 'react'
function Sheet() {
const data = require('../store/db.json')
const mySheet = data.sheet1
return (
<>
<table>
<tbody>
{
Object.entries(mySheet).forEach(([row, cols]) => (
<tr key={row}>
{
Object.entries(cols).forEach(([col, cell]) => (
<td key={`${row},${col}`}>
{cell}
</td>
))
}
</tr>
))
}
</tbody>
</table>
</>
)
}
export default Sheet
db.json
{
"sheet1": {
"1": {
"1": "1,1",
"2": "1,2",
"3": "1,3"
},
"2": {
"1": "2,1",
"2": "2,2",
"3": "2,3"
},
"3": {
"1": "3,1",
"2": "3,2",
"3": "3,3"
}
}
}
.forEach
JS数组方法总是returns undefined
.
console.log([1, 2, 3].forEach(x => x * 2)) // -> undefined
如果您想 return 来自源数组的另一个数组,请使用 .map
console.log([1, 2, 3].map(x => x * 2)) // [2, 4, 6]