【发布时间】:2019-11-23 13:12:10
【问题描述】:
在 ReactJS 中使用多个 javascript 方法创建一个 html 表。 Object.keys 用于从对象中提取数据。在渲染 thead th's 和 tbody tr 和 td's 而没有收到消息时遇到问题,“期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions”。
import React from 'react';
const CreateTable = ({ results }) => {
//headers should be based on keys
const CreateHeaders = () => {
return (
<thead>
<tr>
{Object.keys(results.header).forEach(function(column){
// console.log(column);
<td>
{column}
</td>
})}
</tr>
</thead>
)
}
const CreateBody = ( ) => {
return (
<tbody>
{Object.keys(results.data).forEach(function(tr){
// console.log(results.data[tr])
<tr>
{CreateRows(results.data[tr])}
</tr>
})}
</tbody>
)
}
const CreateRows = (tr) => {
return(
Object.keys(tr).forEach(function(td){
console.log(tr[td]);
<td>{tr[td]}</td>
}));
}
if( results.data !== null && results.data !== undefined){
console.log(<table>{CreateHeaders()}{CreateBody()}</table>);
return <table>{CreateHeaders()}{CreateBody()}</table>
}
else {
return (null);
}
}
export { CreateTable }
我希望呈现一个表格,但我收到一条消息说明,
第 12 行:应为赋值或函数调用,但看到的是表达式 no-unused-expressions 第 26 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions 第 38 行:期望一个赋值或函数调用,但看到一个表达式 no-unused-expressions
我可以在 object.keys 函数中设置一个返回值,但是当我什么都不做时,只会渲染表格的骨架。浏览器
<table><thead></thead><tbody></tbody></table>
上面代码底部的 if 语句的 Console.log 输出
{$$typeof: Symbol(react.element), type: "table", key: null, ref: null, props: {…}, …}
$$typeof: Symbol(react.element)
key: null
props:
children: Array(2)
0:
$$typeof: Symbol(react.element)
key: null
props:
children:
$$typeof: Symbol(react.element)
key: null
props: {children: undefined}
ref: null
type: "tr"
_owner: FiberNode {tag: 0, key: null, elementType: ƒ, type: ƒ, stateNode: null, …}
_store: {validated: true}
_self: null
_source: {fileName: "...\src\components\table.js", lineNumber: 10}
__proto__: Object
__proto__: Object
ref: null
type: "thead"
_owner: FiberNode {tag: 0, key: null, elementType: ƒ, type: ƒ, stateNode: null, …}
_store: {validated: true}
_self: null
_source: {fileName: "...\src\components\table.js", lineNumber: 9}
__proto__: Object
1:
$$typeof: Symbol(react.element)
key: null
props: {children: undefined}
ref: null
type: "tbody"
_owner: FiberNode {tag: 0, key: null, elementType: ƒ, type: ƒ, stateNode: null, …}
_store: {validated: true}
_self: null
_source: {fileName: "...\src\components\table.js", lineNumber: 24}
__proto__: Object
length: 2
__proto__: Array(0)
__proto__: Object
ref: null
type: "table"
【问题讨论】:
-
能否提供
console.log的输出? -
forEach不返回任何内容,请使用map -
1) 你想要
map而不是forEach,因为后者返回未定义。 2) 然后你需要从迭代函数return (<td>...)实际返回 3) 请记住Object.keys中的键顺序不能保证。
标签: javascript reactjs