反应带有数组道具错误更新的子组件

时间:2019-09-11 19:07:27

标签: javascript arrays reactjs typescript setstate

我的React Web应用使用Typescript。

我在使用setState更新父级中的数组时,数组Props的子组件出现问题。

在父Component渲染中声明子对象,如下所示(Alarms是子Component,filteredStatus是数组):

#word-section

子级将数组显示为表格。

<div key={1} className={'1'}>
  <span className='text'><b>{locationName} <i>Status</i></b></span>
  <Alarms filteredStatus={this.state.filteredStatus}/>
</div>

filteredStatus在计时器中由父级更新... 创建一个新的状态数组,并将其分配给state.filtered状态,如下所示:

public generate = () => {
    return this.props.filteredStatus.map(status =>
    {
      return (
      <TableRow key={status.location}>
        <TableCell align="left">
          {(status.severity === 40) && <ErrorIcon style={{ fill: '#FF3333'}}/>}
          {(status.severity === 30) && <NotificationIcon style={{ fill: 'FFA033'}}/>}
          {(status.severity === 20) && <WarningIcon style={{ fill: 'FFE033'}}/>}
        </TableCell>
        <TableCell align="left">{status.description}</TableCell>
        <TableCell align="left">{status.timestamp}</TableCell>
        <TableCell align="left">{status.location}</TableCell>

        {/* <div className="ListBtn">
          <Tooltip title={"Clear '" + alarm.who + "'"}>
            <Avatar>
              <IconButton aria-label="Delete" onClick={this.openClearAlarmConfirmDialog.bind(this, alarm)} >
                <DeleteIcon />
              </IconButton>
            </Avatar>
          </Tooltip>
        </div> */}
      </TableRow>
      );
    });
  }

  public render() {
    return (
      <div>
        {/* <Paper> */}
          <Table>
            <TableHead>
              <TableCell align="left">Severity</TableCell>
              <TableCell align="left">Description</TableCell>
              <TableCell align="left">Timestamp</TableCell>
              <TableCell align="left">Location</TableCell>
            </TableHead>
            <TableBody>
              {this.generate()}
            </TableBody>
          </Table>
        {/* </Paper> */}
      </div>
    );
  }


filteredStatus is declared in the parent Component state as...

    interface IState {
      dtName: string;
      dtDesc: string;
      dtInfo: IDrivetrainInfo;
      drillDownIndex: number;
      componentName: string;
      navLocations: string[];
      filteredStatus: Status[];
      nullStatus: Status[];
      locationStatus: Status;
    }

Status is a user defined class...


    export class Status {
        public location: string;
        public timestamp: string;
        public severity: number;
        public description: string;
    }

发生的事情是,更新后的表未正确显示新的组件数组。新阵列似乎已与旧阵列合并。我将数组的大小添加到了子显示中,有时大小显示为0,而列表显示了15个元素。

我能够通过首先将filteredStatus设置为空数组,然后将新数组设置如下来解决此问题:

this.setState({filteredStatus: this.localStatus});

我可能做错了什么,但这似乎是在子Component中呈现数组道具的问题。

1 个答案:

答案 0 :(得分:0)

表格键...

<TableRow key={status.location}>

根据状态位置而改变。表键必须保持不变,渲染才能正常工作。