gpt4 book ai didi

javascript - 我如何解构此 react 组件中的对象状态数组以使用单个字段数据

转载 作者:行者123 更新时间:2023-11-30 09:11:29 25 4
gpt4 key购买 nike

在获取之后,组件状态的数组中有 96 个对象。除了年份和某些情况下的月份之外,它们都是独一无二的对象。年份不能一成不变,因为它显然会在某个时候发生变化。月份将从 Integer 转换为 String。我已尝试对其进行映射,但出现错误,提示 cannot read property map of undefined。但是,如果我 console.log 数据,我将得到包含 96 个对象的数组。当我尝试对其进行解构时,出现错误 Invalid attempt to destructure non-iterable instance我的主要目标是获取年份并将其作为模板文字传递给 headerName,以便它作为下面所有数据的分组列加载。并获取月份整数并将其转换为该月份的字符串我的这个组件的代码如下。

import React, { Component } from "react";
import { AgGridReact } from "ag-grid-react";

class ColumnGroups extends Component {
constructor(props) {
super(props);

this.state = {
columnDefs: [
{
headerName: "Year",
field: "year",
children: [
{
headerName: "Month",
field: "month",
width: 150,
children: [
{
headerName: "Sold",
field: "sales",
width: 150
},
{
headerName: "Return",
field: "returns",
width: 150
},
{
headerName: "RMA%",
field: "rma",
width: 150
}
]
}

],
defaultColDef: {
editable: false,
sortable: true,
resizable: true,
filter: true
},
rowSelection: "multiple",
rowGroupPanelShow: "always",
pivotPanelShow: "always",
paginationPageSize: 10,
paginationNumberFormatter: function(params) {
return "[" + params.value.toLocaleString() + "]";
},
rowData: []


}

],
}

}
onGridReady = params => {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;

const httpRequest = new XMLHttpRequest();
const updateData = data => {
this.setState({ rowData: data });
params.api.paginationGoToPage(4);
};

httpRequest.open(
"GET",
"http://localhost:5000/api/salessummary"
);
httpRequest.send();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
updateData(JSON.parse(httpRequest.responseText));
}
};
};

onPageSizeChanged(newPageSize) {
var value = document.getElementById("page-size").value;
this.gridApi.paginationSetPageSize(Number(value));
}

render() {
{console.log(this.state.rowData)}
return (
<div>
<div>
<div
className="ag-theme-balham"
style={{
height: '500px',
width: '100%' }}
>
<div className="test-header">
Page Size:
<select onChange={this.onPageSizeChanged.bind(this)} id="page-size">
<option value="10" selected="">
10
</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="1000">1000</option>
</select>
</div>
<AgGridReact
columnDefs={this.state.columnDefs}
rowData={this.state.rowData}
autoGroupColumnDef={this.state.autoGroupColumnDef}
defaultColDef={this.state.defaultColDef}
suppressRowClickSelection={true}
groupSelectsChildren={true}
debug={true}
rowSelection={this.state.rowSelection}
rowGroupPanelShow={this.state.rowGroupPanelShow}
pivotPanelShow={this.state.pivotPanelShow}
enableRangeSelection={true}
pagination={true}
paginationPageSize={this.state.paginationPageSize}
paginationNumberFormatter={this.state.paginationNumberFormatter}
onGridReady={this.onGridReady}
>

</AgGridReact>
</div>
</div>
</div>

)
}
}
export default ColumnGroups;

这是返回的部分 Cannot read property 'map' of undefined

   <div>
{
this.state.rowData.map(data => <div>{data.year}</div> )
}
</div>

数据如下

{
"year": 2019,
"month": 4,
"productStyle": "zzzzz",
"sales": 1,
"returns": 0,
"rma": 0
},

每一年都是一样的。映射返回 96 年 95 其中我不需要。它会改变,我希望这对实地年来说是动态的。我需要访问月份,以便我可以将 integer 更改为 string 3 以表示 April 等。

最佳答案

没有内置的 JS 方法可以将月份数字格式化为您可以构建自己的字符串:

numToMonth(n){
switch(n){
case 1:
return 'Jan'
//... all months
default:
return 'Dec'
}
}

您需要在映射之前进行验证。要格外彻底地检查它是否存在并且它是一个数组:

render(){
if(this.state.rowData && Array.isArray(this.state.rowData)){
var items = this.state.rowData
}
return(
<div>
{items && items.map(item => <div>{item.Year}</div> )}
</div>
)
}
}

如果您需要基于当前年份的一项,请使用查找:

render(){
if(this.state.rowData && Array.isArray(this.state.rowData)){
var item = this.state.rowData.find(data => data.year === new Date().getFullYear )
}

return(
<div>
{item && `${item.year} - ${this.numToMonth(item.month)}` }
</div>
)
}

如果您需要许多基于当前年份过滤器的项目:

render(){
if(this.state.rowData && Array.isArray(this.state.rowData)){
var items = this.state.rowData.filter(data => data.year === new Date().getFullYear )
}

return(
<div>
{item && items.map(items=> <div>{item.year} - {this.numToMonth(item.month)} </div>})
</div>
)
}

如果所有年份都相同,并且您需要和一堆月份数字作为字符串:

render(){
if(this.state.rowData && Array.isArray(this.state.rowData)){
var items = this.state.rowData
}
return(
<div>
{items && items[0].year}
{items && items.map(item => <div>{this.numToMonth(item.month)}</div> )}
</div>
)
}
}

最后一个例子的可运行片段:

class SomeComponent extends React.Component {
state={
rowData:[
{year:1988,month:1},
{year:1988,month:3},
{year:1988,month:2},
{year:1988,month:1},
]
}
numToMonth(n){
switch(n){
case 1:
return 'Jan'
case 2:
return 'Feb'
case 3:
return 'March'
//... all months
default:
return 'Dec'
}
}
render(){
if(this.state.rowData && Array.isArray(this.state.rowData)){
var items = this.state.rowData
}
return(
<div>
{items && items[0].year}
{items && items.map(item => <div>{this.numToMonth(item.month)}</div> )}
</div>
)
}
}

ReactDOM.render(
<SomeComponent />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="react"></div>

关于javascript - 我如何解构此 react 组件中的对象状态数组以使用单个字段数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58593627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com