如果键是相同的,React忽略props是数组缓冲区更新元素吗?



我想知道React如何决定重新渲染某些元素。我有一个应用程序,然后用户切换标签,我更新一个<AssetContainer>。有时,该容器将包含用于密钥的asset和相同的document_id。我注意到,当我创建一个资产时,我的效果运行将缩略图URL设置为blob fine。我切换选项卡,用相同的文件创建一个资源,它会生成另一个新的blob。然后,当我切换回第一个标签,它不会重新渲染。尽管在新的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>都会按预期呈现。每次在<AssetView>返回之前,我都看到console.log着火。然而,当key与以前相同时,当数组缓冲区prop更新时,<Asset>useEffect不会触发。不知道为什么。

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

我认为问题是key对于两个选项卡是相同的(我将修复),但我不确定需要多高(如果可能的话)React忽略key。如果只有key导致缓存,它甚至不应该生成Blob-2。

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

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

否则,效果只会对空数组

运行一次