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

时间:2020-05-07 17:46:28

标签: javascript reactjs react-hooks use-ref

我想获取状态的最新值并以内联样式使用它,但是它首先返回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}
...

1 个答案:

答案 0 :(得分:0)

您不需要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