【问题标题】:Functions are not valid as a React child. The app runs correctly but getting the warning anyway函数作为 React 子级无效。该应用程序运行正常,但仍然收到警告
【发布时间】:2021-10-07 14:58:27
【问题描述】:

我收到以下警告,但应用程序运行正常:

函数作为 React 子级无效。如果您可能会发生这种情况 返回一个组件而不是从渲染。或者也许你 意味着调用这个函数而不是返回它。 在 div 中(在 MyCollection.tsx:16)

export default function MyCollection(props:any ) {
  let nodes = useSelector((state: any) => state.vpms.norm.nodes);
  // let node = useSelector((state: any) => state.vpms.norm.nodes[props.id]);
  const groupListAdapter: GroupListAdapter = useGroupList(props);
  let items: any = [];
  groupListAdapter.itemsIds().forEach((itemId:any) => {items.push(nodes[itemId])});

  const getItems = items.map((item: any, index: number) =>
        <div key={index}>
          {props.render}
        </div>
    )

  return (
      <>
        {getItems}
      </>
  );
}

但我不能称它为{getItems()},因为它是一个数组。

{props.render}是;

<MyCollection id={id(persons, 'coverages')} 
   render= {(coverages: any, index: number) => (
   <Accordion id={coverages.id} isExpanded={true}  >
   <Grid columns={4} style={{width: "100%"}} >
   <Cell width={calculateWidth(2, 4)}>
      <Checkbox id={id(coverages, "assured_editable")} labelPosition='before'  tabId={persons.id} styleIds={[]}   />
   </Cell>
...

【问题讨论】:

  • getItems 是一个数组,而不是一个函数;什么是 props.render?

标签: reactjs typescript


【解决方案1】:

Array.map() 的返回值是一个新数组:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#return_value

不需要添加这些括号,因为您不需要将其作为函数调用。你有一个以数组为值的常量。

去掉那些括号就可以了。

【讨论】:

  • 是的,我删除了括号,它们最初不存在,但我收到警告:函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用此函数而不是返回它。在 div 中(在 MyCollection.tsx:16)
  • 我想,问题是关于{props.render}。这里到底发生了什么?这些是children吗?
  • props.render 是: (
【解决方案2】:

是的,@Michael Czechowski,问题是 {props.render}

我是这样改的,效果很好:

const getItems = items.map((item: any, index: number) =>
        <div key={index}>
          {props.render(item, index)}
        </div>
    )

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 2018-12-15
    • 1970-01-01
    • 2018-11-05
    • 2020-03-09
    • 2021-01-03
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多