reactjs - 如果键相同,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>
。但是,当数组缓冲区道具更新时,useEffect
of与以前相同时不会触发。不确定为什么。<Asset>
key
更新为什么在效果中执行 [thumbnail] 不是答案 这不是问题,因为由于重新安装了更高级别的组件,事情更新得很好。如果我执行此建议,则每次切换选项卡时都会重新运行使用效果并生成一个新的 blob URL,这不是我想要的。行为原样是在选项卡 A 中它将生成 Blob-1,在选项卡 B 中它将生成 Blob-2。当我回到 Tab AI 想要 Blob-1 但仍然得到 Blob-2。
我认为问题在于key
两个选项卡的key
. 如果只是key
导致缓存的原因,它甚至不应该生成 Blob-2。
解决方案
推荐阅读
- amazon-web-services - HITLayoutParameters怎么填
- reactjs - 如何在 nextjs 的 getinitial 道具中获取 cookie?
- prisma - 一种数据类型中两个字段的相同关系
- r - 将自定义函数应用于 r 中的每一行
- javascript - 如何在 react-redux-typescript 中将存储状态作为道具传递?
- django - 在 django 3.0 上为 include() 提供命名空间参数
- javascript - 如何在 JavaScript 中处理 XPath 的子元素中的命名空间声明?
- python - 寻找小数 1/n 小数的周期
- ember.js - Ember JS 路由器 - 如何为错误页面生成 404 Http 响应代码
- swift - 如何在 SwiftUI 中实现 MVVM 模式?视图不会重新渲染