【问题标题】:React typescript recognizes array as objectReact typescript 将数组识别为对象
【发布时间】:2021-10-01 20:49:15
【问题描述】:

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 处中断。有人可以帮帮我吗?我觉得我错过了一些小事。

【问题讨论】:

  • 你在控制台记录'row',而它应该是row
  • 在此之前它失败了,那只是一个占位符

标签: reactjs typescript jsx tsx react-tsx


【解决方案1】:

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>;
}

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2022-09-27
    • 2013-04-20
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多