首页 > 解决方案 > 使用 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,而应从变量缓存中获取。上述情况的问题是,当数组中的第二项用于渲染子组件时,它没有获得我们在第一次渲染中设置的值(使用数组中的第一项)。我怎样才能做到这一点?

标签: javascriptreactjs

解决方案


推荐阅读