我的 App.js 看起来像这样:
import ChildComponent from "./ChildComponent";
import { useState, useMemo, useCallback } from "react";
export default function App() {
const [pageTitle, setPageTitle] = useState("");
const [anotherProp, setAnotherProp] = useState(1);
const handleInputChange = useCallback(
(e) => {
setPageTitle(e.target.value);
},
[pageTitle]
);
const handleIncrement = useCallback(() => {
setAnotherProp(anotherProp + 1);
}, [anotherProp]);
return (
<div className="App">
<ChildComponent title={pageTitle} handleInputChange={handleInputChange} />
<div>
{anotherProp}
<input
type={"button"}
value={"Increment Count"}
onClick={handleIncrement}
/>
</div>
</div>
);
}
子组件如下所示:
function ChildComponent({ title, handleInputChange }) {
console.log("Child Component renders");
return (
<>
<input type="text" onChange={handleInputChange} />
<h1>{title}</h1>
</>
);
}
export default ChildComponent;
因为我已经使用过,所以useCallBack
我希望当我单击按钮来增加计数时,我的子组件应该保持不受影响并且不会重新渲染。但我的子组件仍然重新渲染。
你能帮我理解为什么吗?
这是 React 的标准行为。当父组件重新渲染时,即使子组件的 props 没有改变,它也会重新渲染其子组件。在这种情况下,您的父级正在重新渲染,因为其状态正在更新(计数器
anotherProp
)。如果您想防止特定组件在其 props 保持不变时重新渲染,您可以
React.memo()
通过将您包装ChildComponent
在其中来使用,例如:这样,
ChildComponent
当 props 保持不变时,React 不会重新渲染你的。顺便说一句,
[pageTitle]
第一个useCallback()
钩子的依赖关系是不必要的,并且可以只是[]
因为您的回调在其中不使用此状态值。另一个版本的答案。useCallback 和 useMemo 的组合
应用程序.js
Child.js
希望这可以帮助。
问题在于 handleInputChange 的 useCallback 中的依赖项数组。您将 pageTitle 作为依赖项,这会导致每当 pageTitle 更改时重新创建 handleInputChange 函数。因此,从依赖项数组中删除 pageTitle 以防止不必要的重新创建,它应该按预期工作。