gpt4 book ai didi

reactjs - useRef 钩子(Hook)不会触发重新渲染

转载 作者:行者123 更新时间:2023-12-04 11:47:30 25 4
gpt4 key购买 nike

出于某种原因,我的测试在使用这样的 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"));
});
});

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

最佳答案

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

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.



这意味着即使 ref 被设置,重新渲染也永远不会发生。您需要通过其他方式触发它,也许通过使用如上所述的回调引用或创建 useEffectcurrent 使用react的钩子(Hook)引用值

关于reactjs - useRef 钩子(Hook)不会触发重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59202434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com