如何使用React处理关键属性来显示组件集合?

时间:2019-02-20 19:20:40

标签: reactjs typescript

我想显示日志数组:

export interface IResult {
  succeeded: boolean;
  logs: IServerLogs;
}

export interface IServerLogs {
    step1: ILog[],
    step2: ILog[],
    step3: ILog[]
}

export interface ILog {
  id: number;
  date: Date;
  msg: string;
  severity: number;
  obj?: any;
}

我在App.tsx中有一个IResult数组

render() {
    return (
    {this.state.results.map((result, index) => (
      <Results key={index} results={result} index={index + 1} />
    ))}
   )

}

在results.tsx中:

render() {
    const { step1, step2, step3 } = this.props.results.logs;
    const { index } = this.props;
    return (
     <div>
            <div>
                #{index} Status: {this.props.results.ret ? "SUCCEEDED" : "FAILED"}
                <FontAwesomeIcon icon={faWindowClose} />
            </div>
            <Accordion>
                { step1.length > 0 && <Result logs={step1}  title="Step 1" /> }
                { step2.length> 0 && <Result logs={step2} title="Step 2" /> }
                { step3.length > 0 && <Result logs={step3}  title="Step 3" /> }
            </Accordion>
        </div>
   )

}

在result.tsx中:

render() {
    const { logs, title } = this.props;
    return (
        <AccordionItem>
            <AccordionItemTitle><b>{title}</b></AccordionItemTitle>
            <AccordionItemBody>
                <Table striped bordered hover size="sm">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Message</th>
                        <th>Obj</th>
                    </tr>
                </thead>
                <tbody>
                {
                    logs.map((log, index) =>
                    (
                        <tr key={log.id} style={{ color: log.severity == 0 ? "green": "red"}}>
                            <td key={index+1+log.id}>{moment(log.date).format("HH:mm:ss")}</td>
                            <td key={index+2+log.id}>{log.msg}</td>
                            <td key={index+3+log.id}>{log.obj}</td>
                        </tr>
                    ))
                }
                </tbody>
            </Table>
            </AccordionItemBody>
        </AccordionItem>
    );
}

使用所有这些东西,我得到以下错误:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
    in td (created by Result)
    in tr (created by Result)
    in tbody (created by Result)
    in table (created by Table)

我尝试在各处设置和删除密钥,但在TR或TD上总是收到相同的错误消息...

我在做什么错了?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我明白了

export interface ILog {
  id: number;
  date: Date;
  msg: string;
  severity: number;
  obj?: any;
}

具有obj类型。因此,如果ILog.obj是对象,则无法渲染。因此,您可能需要添加一个检查,检查其对象是否呈现了对象的属性,否则呈现了obj。