javascript - 使用 JS 对象作为 API 的缓存
问题描述
const ParentComponent = () => {
const [cache,setCache] = useState({});
const data = [{url:"http://.."} , {url:"http://.."} , {url:"http://.."}];
return (
data.map( item,ind => (<ChildComponent item={item} setCache={setCache} cache={cache} /> ) )
)
}
const ChildComponent = ({item,setCache,cache}) => {
const [img,setImg] = useState(null);
useEffect(() => {
const setVal = async () => {
const val = await getProfilePic(item.url); //api
setCache({...cache ,[item.url]:val})
setImg(val);
};
if(cache[item.url])
{ return setImg(cache[item.url]) }
else { setVal(); }
} ,[])
return (
<div> <img src={img} /> </div>
)
}
这里数组变量data中的url可以相同。在这种情况下,它不应再次调用 API,而应从变量缓存中获取。上述情况的问题是,当数组中的第二项用于渲染子组件时,它没有获得我们在第一次渲染中设置的值(使用数组中的第一项)。我怎样才能做到这一点?
解决方案
推荐阅读
- c# - 使用 HttpClientFactory “无法对套接字执行操作”
- python - 文件的条件写入和解析(如果 elif else)
- github - 无法直接从 Atom IDE 初始化和推送 Github 存储库
- php - 如何创建二维数组到多级订单列表?
- typescript - 有没有办法强类型 sagas put 动作?
- flutter - Future Builder 返回 Null
- python - 将输入形状作为特征和标签数量的总和是否错误
- html - 当页面宽度减小时如何将文本换行
- augmented-reality - ARCore - 增强图像检测是否适用于前置摄像头?
- html - 将粘性位置分配给网格中的侧边栏