繁体   English   中英

无法获取更新的 state 值 useState 和 UseEffect

[英]Cannot get the updated the state value useState and UseEffect

我想获取 state 的最新值并使用它内联样式,但它首先返回 0 值,然后渲染更新了 state。 但是,我无法将值分配给样式。

const ImageCard = ({ image: { alt_description, urls } }) => {
  const [spans, setSpans] = useState(0);
  const imageRef = useRef(null);

  useEffect(() => imageRef.current.addEventListener('load', () => {
    const height = imageRef.current.clientHeight;
    const spans = Math.ceil(height / 10);
    setSpans({ spans });
  }));

  return (
    <div style={{ gridRowEnd: `span ${spans}` }}>
      <img ref={imageRef} alt={alt_description} src={urls.regular} />
    </div>
  );
}

控制台 output:

10 0
{spans: 15}
{spans: 33}
...

为此,您不需要useEffect 您可以使用 img 标签的onLoad事件,如下所示:

const ImageCard = ({ image: { alt_description, urls } }) => {
  const [spans, setSpans] = useState(0);

  const imageLoaded = e => {
    const height = e.currentTarget.clientHeight;
    const spans = Math.ceil(height / 10);
    setSpans({ spans });
  };
  //Dont forget to remove this line
  console.log(spans);
  return (
    <div style={{ gridRowEnd: `span ${spans}` }}>
      <img onLoad={imageLoaded} alt={alt_description} src={urls.regular} />
    </div>
  );
};

工作代码沙箱示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM