无法获取更新的状态值 useState 和 UseEffect

Cannot get the updated the state value useState and UseEffect

我想获取状态的最新值并使用它的内联样式,但它首先是 returns 0 个值,然后渲染更新了状态。但是,我无法将值分配到样式中。

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>
  );
}

控制台输出:

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>
  );
};

Working code sandbox example