React typescript 将数组识别为对象

问题描述

一般来说是 React 和 js 的新手,所以这可能是一个愚蠢的问题,但我无法解决

我有一个像这样的组件:

export interface TableViewContainerProps {
    header: WorthSummaryContainerProps
    content: TableViewRowProps[]
}

export const TableViewContainer = (props: TableViewContainerProps) => {
    console.log('content type is ',typeof(props.content))
    console.log('content is ',props.content)
    return (
        <div id="tableview-container">
            <div id="tableview">
                <TableViewHeader {...props.header}/>
                <TableViewContentList {...props.content} />
                <div id="tableview-footer">
                </div>
            </div>
        </div>
    )
}

所以当我打印它时它是一个对象数组,一切都很好。 TableViewContentList 获取内容作为道具:

export const TableViewContentList = (props: TableViewRowProps[]) => {
    console.log('type of TableViewContentList props is: ',typeof(props),props)
    const tableViewContents = props.map((row) => console.log('row'))

    return (
        <div id="tableview-content-list">
            {tableViewContents}
        </div>
    )
}

所以当我在这里打印它时,它不再是一个对象,而是在 .map 处中断。有人可以帮我吗?我觉得我错过了一些小事。

解决方法

Spread syntax (...) 将在您将其应用于对象内的数组时为您提供一个对象。

type TableViewRowProps  = number;
interface TableViewContainerProps {
    content: TableViewRowProps[]
}

const props = {content: [1,2,3]}

const b = {...props.content}
console.log(b) // { "0": 1,"1": 2,"2": 3 }. 

所以 TableViewContentList 获得了道具:props[0]props[1]props[2],这是错误的。

传递给组件的所有属性都将附加在 props 中,这就是您获得对象的原因。 props 将始终是一个对象。所以你最好像这样传递 content

<TableViewContentList {...props} />

或者这个:

<TableViewContentList content={props.content} />

然后你可以将它映射到行:

export default function TableViewContentList(props: { content: TableViewRowProps[] }) {
  const tableViewContents = props.content.map((row) => console.log('row'));

  return <div id="tableview-content-list">{tableViewContents}</div>;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...