在下面的代码中onDataChange
的Form element
的 prop 从 .CSV 通过组件中的Papa.parse
Form
到 JSON,并在CommonComponent
状态更新data
。
在选择 .CSV 文件Keys: Object.keys(this.props.data[0])
显示错误,指出this.props.data[0]
null
。但是,{this.props.data.map(data=> <TableRows key={data.id} {...data}/>)}
工作正常并等待data
更新和呈现,即使它们都在开始时null
。
有什么办法可以处理这种情况吗?我想使用Object.keys(this.props.data[0])
(即 Array 第一个对象的键(来显示表头,因为对于不同的.CSV表头会有所不同,我想为任何大小或比例呈现表格。.CSV。
这是我的代码,我没有显示Form
组件,因为它无关紧要。
const TableRows = (props) => {
return (
<tr>
<td>{props.Account_Created}</td>
<td>{props.City}</td>
<td>{props.Country}</td>
<td>{props.Last_Login}</td>
</tr>
);
};
class TableComponent extends Component {
state = {
Keys: []
};
componentDidMount() {
this.setState({
Keys: Object.keys(this.props.data[0])
})
}
render() {
return (
<div>
<table border="1">
<thead>
<tr>
{this.state.Keys.map(KEY => <th>{KEY}</th>)}
</tr>
</thead>
<tbody>
{this.props.data.map(data=> <TableRows key={data.id} {...data}/>)}
</tbody>
</table>
</div>
);
}
}
class CommonComponent extends Component {
state = {
data: []
};
updateData = (result) => {
const data = result.data;
this.setState({data});
};
render() {
return (
<div>
<Form onDataChange={this.updateData}/>
<TableComponent data={this.state.data}/>
</div>
);
}
}
不要使用componentDidMount
您的问题是您使用componentDidMount
从数据对象获取keys
。当组件挂载时,很可能还没有数据。
解决方案:获取render
中的密钥。这将更好地工作,原因有两个:
- 您不必担心等待数据到达,组件将在到达时更新。
- 如果您更改了数据,标题也会更改。
这是代码:
render() {
return (
<div>
<table border="1">
<thead>
<tr>
{ this.props.data.length > 0 ? Object.keys(this.props.data[0]).map(KEY => <th>{KEY}</th>) : ''}
</tr>
</thead>
<tbody>
{this.props.data.map(data=> <TableRows key={data.id} {...data}/>)}
</tbody>
</table>
</div>
);
}
我得到了解决方案,现在我可以显示通过 props 进入TableComponent
的任何 JSON 数据。这是我问题的解决方案,我在考虑了 chbchb55 的回复后提出:
class TableRows extends Component {
render() {
return (
<tr>
{this.props.keys.map(Key=> <td>{this.props.data[Key]}</td>)}
</tr>
);
}
}
class Table extends Component {
render() {
return (
<table>
<thead>
<tr>
{this.props.keys.map(Key => <th>{Key}</th>)}
</tr>
</thead>
<tbody>
{this.props.data.map(data=> <TableRows key={data.id} keys={this.props.keys} data={data}/>)}
</tbody>
</table>
);
}
}
class TableComponent extends Component {
render() {
return (
<div>
<Table keys={this.props.data.length > 0 ? Object.keys(this.props.data[0]) : []} data={this.props.data}/>
</div>
);
}
}