如何使用react修复错误“无法在回调函数内调用react use hook”?

IT技术 reactjs typescript react-hooks
2021-05-25 00:59:23

我在返回语句中使用名为 useGetCompanyByItemId 的 useHook。

所以我收到错误“无法在回调函数中调用react-hooks”

我想做什么?

我正在查询ownitems 和shareditems。

我显示这两个项目。在 Content div 中我做映射,在那里我调用 useGetCompanyByItemId 钩子,我得到错误。

下面是我的代码,

function Parent() {
    const ownedItems = [{ //somearray of objects}];
    const sharedItems = [{//somearray of objects}];
    const getCurrentItems = () => {
        return ownedItems.concat(sharedItems);
    }

    return (
        <Wrapper>
            {getCurrentItems.length> 0 &&
                <FirstWrapper>
                    //somedivs
                </FirstWrapper>
                <Content>
                    {springProps.map((index) => {
                        const item = getCurrentItems()[index];
                        const isSharedItem = item && item.cognitoId !== cognitoId;
                        const company = useGetCompanyByItemId(item.id); //here is the error
                        return (
                            <>
                                {isSharedItem && 
                                     <div>
                                         <span>company</span>
                                     </div>
                                 }
                            </>
                        }
                    )
                }
            );
        </Content>
    </Wrapper>
);

}

我不知道如何解决这个问题。我需要为 useGetCompanyById 钩子传递 item.id,但我不知道如何从 return 语句外部传递 item.id,因为这将修复该错误。

有人可以帮我解决这个错误。谢谢。

2个回答

我可以在这里看到两种重构方式:

选项 1:如果您无法控制要修改的自定义钩子

将迭代提取到一个组件中:

const Company = ({itemId, isSharedItem}) => {
   const company = useGetCompanyByItemId(itemId);
   return (<>
      {isSharedItem && 
          (<div>
             <span>{company}</span>
           </div>)
      }
      </>);
}

迭代时使用上述组件。

选项 2:如果您可以控制自定义钩子: 我建议重构自定义钩子以返回一个方法而不是对象。示例用法:

const {getCompanyByItemId} = useFetchCompany();

. . .

代码中的任何地方, getCompanyByItemId(itemId)

上述选项的明显优势:

  • 可读和可扩展,可以在任何地方使用,甚至可以传递
  • 您不必担心重构和代码拆分只是为了不破坏钩子规则(当然,如果有意义就这样做)。

将此逻辑提取到组件

function Item({ item, isSharedItem }) {
  const company = useGetCompanyByItemId(item.id);
  return (
    <>
      {isSharedItem && (
        <div>
          <span>company</span>
        </div>
      )}
    </>
  );
}

然后在你的循环中使用它

springProps.map((index) => {
  ...
  return <Item item={item} isSharedItem={isSharedItem} key={index} />