useRef钩子不触发重新渲染

时间:2019-12-05 19:56:07

标签: reactjs react-hooks

由于某种原因,使用这样的ref时,我的测试未通过:

import React, { useRef } from "react";
import { waitForElement, render } from "@testing-library/react";

const MyComponent = props => {
  const elementRef = useRef(null);
  return (
    <div>
      <div ref={elementRef} />
      {elementRef.current && <div data-testid="test-div" />}
    </div>
  );
};

describe("MyComponent", () => {
  it("test-div should exist when the ref is set", async done => {
    const { getByTestId } = render(<MyComponent />);
    await waitForElement(() => getByTestId("test-div"));
  });
});

知道为什么这不起作用吗?

1 个答案:

答案 0 :(得分:1)

不是测试无效,而是“ test-div”的呈现。如果尝试在测试之外渲染此组件,则将获得相同的结果。如React Documentation中所述:

  

请记住,当useRef的内容更改时,它不会通知您。更改.current属性不会导致重新渲染。如果您想在React将ref附加或分离到DOM节点时运行一些代码,则可能要改用回调ref。

这意味着即使设置了参考,重渲染也不会发生。您可能需要通过其他方式来触发它,例如通过使用如上所述的回调ref或创建一个对ref的useEffect值有反应的current钩子。

相关问题