首页 > 解决方案 > 如果键相同,React 是否会忽略作为用于更新元素的数组缓冲区的道具?

问题描述

我想知道 React 如何决定重新渲染某些元素。我有一个应用程序,然后用户切换选项卡,我更新一个<AssetContainer>. 有时,该容器将包含一个asset与密钥相同的容器document_id。我注意到,当我创建资产时,我的效果会运行以将缩略图 URL 设置为 blob 罚款。我切换选项卡,使用相同的文件创建一个资产,然后它会生成另一个新的 blob。然后当我切换回第一个选项卡时,它不会重新渲染。尽管在 new 中被传递asset.thumbnail.image,但它仍将其视为相同。我应该注意asset.thumbnail.image的是一个数组缓冲区。这是否会使 React 在查找更新时忽略该值?

我有这样的代码:

<AssetContainer>
{assets.map((asset) => (
      <Asset
        key={asset.document_id}
        thumbnail={asset.thumbnail!.image!}
        thumbnailFormat={asset.thumbnail!.format!}
        hasClaim={!!asset.provenance}
        errors={asset.errors}
        size="80px"
      />
    )
)}
</AssetContainer>

<Asset>我有以下效果和代码,<AssetView thumbnailUrl={thumbnailUrl} size={size}></AssetView>其中定义为:

// The effect in Asset
useEffect(() => {
  let blobUrl;
  if (thumbnail) {
    const imgData = Array.isArray(thumbnail)
      ? thumbnail
      : new Uint8Array(Object.values(thumbnail));
    const blob = new Blob([imgData], { type: thumbnailFormat });
    blobUrl = URL.createObjectURL(blob);
    // this is what stops firing every time i switch tabs which should re-render the elements based on new data in the tab
    console.log('setting thumbnail url', blobUrl);
    setThumbnailUrl(blobUrl);
  }
  return () => {
    if (blobUrl) {
      URL.revokeObjectURL(blobUrl);
    }
  };
}, []);

// The AssetView definition for the tag invocation above
const AssetView = styled.div`
  display: inline-flex;
  align-items: flex-end;
  justify-content: flex-end;
  flex-shrink: 0;
  width: ${(props) => props.size};
  height: ${(props) => props.size};
  margin-right: 4px;
  margin-bottom: 4px;
  border-radius: 2px;
  background-color: #434646;
  background-image: ${(props) =>
    props.thumbnailUrl ? `url("${props.thumbnailUrl}")` : 'none'};
  background-size: contain;
  background-position: center;
`;

简短的版本是这样的:每次我切换标签时,都会<Asset>按预期呈现。console.log每次回来之前我都会看到一场火灾<AssetView>。但是,当数组缓冲区道具更新时,useEffectof与以前相同时不会触发。不确定为什么。<Asset>key

更新为什么在效果中执行 [thumbnail] 不是答案 这不是问题,因为由于重新安装了更高级别的组件,事情更新得很好。如果我执行此建议,则每次切换选项卡时都会重新运行使用效果并生成一个新的 blob URL,这不是我想要的。行为原样是在选项卡 A 中它将生成 Blob-1,在选项卡 B 中它将生成 Blob-2。当我回到 Tab AI 想要 Blob-1 但仍然得到 Blob-2。

我认为问题在于key两个选项卡的key. 如果只是key导致缓存的原因,它甚至不应该生成 Blob-2。

标签: reactjsreact-hooks

解决方案


thumbnail应该包含在您的效果依赖项数组中吗?

useEffect(() => {
    // ...
}, [props.thumbnail]);

否则,效果只会使用空数组运行一次


推荐阅读