2

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

所以我收到错误“无法在回调函数中调用反应挂钩”

我想做什么?

我正在查询拥有的物品和共享物品。

我显示这两个项目。在内容 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,因为这样可以修复该错误。

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

4

2 回答 2

1

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

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

将迭代提取到组件中:

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

在迭代时使用上述组件。

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

const {getCompanyByItemId} = useFetchCompany();

. . .

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

上述选项的明显优势:

  • 可读且可扩展,可在任何地方使用,甚至可以四处传递
  • 您不必担心重构和代码拆分只是为了不破坏钩子规则(当然,如果有意义就这样做)。
于 2020-07-29T12:06:59.803 回答
0

将此逻辑提取到组件中

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} />
于 2020-07-29T11:54:46.030 回答