【问题标题】:How to pass an array of objects as a prop in react?如何在反应中将对象数组作为道具传递?
【发布时间】:2020-11-16 17:36:17
【问题描述】:

我试图在反应时将对象数组传递给一个函数,我收到 Uncaught TypeError: props.map is not a function 尽管当我将道具(即用户)打印到日志之前传递它,它是一个数组

我有以下数据:

{
"name": "My test name",
"users": [
    {
        "name": "user 1 name",
        "data": [
            {
                "var1": [],
                "var2": {
                    "sub1": "open",
                    "sub2": ""
                },
            },
            {
                "var1": [],
                "var2": {
                    "sub1": "close",
                    "sub2": ""
                },
            },
        ]
    }
]}

数据由 REST API 调用接收。 我正在尝试使用以下反应代码处理它:

interface SingleUser {
  var1: string[];
  var2: {
    sub1: string;
    sub2: string;
  }
  
}
interface Users {
    name: string;
    users:SingleUser[];
}

render() {
const { name, users} = this.state;
return (
  <div className='flow d-flex flex-row flex-wrap justify-content-start'>
    <GenInfo name={name} />
    <MyTabs {...users}/>
  </div>
);}



function MyTabs(props: Users[]) {
  const data = props
  const tabs = props.map((item) => {
    return {
      tabId: item.name.replace(/ /g,"_"),
      label: item.name,
      content: <TestTable {...item.users} />
    }
  });
  return <HorizontalTabs tabs={tabs} pills />
}

【问题讨论】:

    标签: reactjs react-props


    【解决方案1】:

    您可以将 props ò MyTabs 定义为这样的数据

    render() {
    const { name, users} = this.state;
    return (
      <div className='flow d-flex flex-row flex-wrap justify-content-start'>
        <GenInfo name={name} />
        <MyTabs data={users}/>
      </div>
    );}
    
    function MyTabs({data: Users[]}) {
      const tabs = data.map((item) => {
        return {
          tabId: item.name.replace(/ /g,"_"),
          label: item.name,
          content: <TestTable {...item.users} />
        }
      });
      return <HorizontalTabs tabs={tabs} pills />
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多