在ReactJS中使用多个javascript方法创建html表。 Object.keys用于从对象中提取数据。在呈现主题,主体,tr和td而不显示消息时出现问题,“预期分配或函数调用,而是看到了表达式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函数内部设置一个返回值,但是当我什么都不做时,除了表的骨架之外,什么都不呈现。 IE浏览器
<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"
答案 0 :(得分:4)
您正在使用没有返回值的forEach
。您正在寻找map
。
<tr>
{Object.keys(results.header).map(column => (
// console.log(column);
<td>
{column}
</td>
))}
</tr>
然后从CreateRows
const CreateRows = (tr) => {
return(
Object.keys(tr).map(td =>
<td>{tr[td]}</td>
));
}