gpt4 book ai didi

javascript - 为什么当 props 没有改变时 React 会重新渲染子元素?

转载 作者:行者123 更新时间:2023-12-02 18:46:31 25 4
gpt4 key购买 nike

考虑以下示例:

import "./styles.css";
import React from "react";

function Children(props) {
const counter = props.counter2;
console.log("re-rendering children");
return (
<div className="App">
<p>counter2 value = {counter} </p>
</div>
);
}

export default function App() {
const [counter, setCounter] = React.useState(0);
const [counter2] = React.useState(0);
return (
<div className="App">
<p>counter value = {counter} </p>
<button onClick={(e) => setCounter((c) => c + 1)}>increment</button>
<Children counter2={counter2} />
</div>
);
}

Children 组件不依赖于父状态 counter,但是当我单击按钮时,我可以看到 re-rendering 日志每次点击时都会打印。如果我没记错的话,这意味着 Children 组件被重新渲染。我的问题是为什么?它不应该重新渲染,因为 Prop 没有改变。

代码沙箱:https://codesandbox.io/s/modern-dawn-xj9b8

最佳答案

由于React的生命周期,当你使用功能组件时,它也被认为是无状态的,并且每次父组件有更新时都会重新渲染,无论传递给子组件的props是否有变化.

有两种方法可以改变这种行为,

  1. 使用类组件并使用shouldComponentUpdate决定是否更新它

  2. 或使用 React.memo 的推荐方式,

import "./styles.css";
import React from "react";

function Children(props) {
const counter = props.counter2;
console.log("re-rendering children");
return (
<div className="App">
<p>counter2 value = {counter} </p>
</div>
);
}

const MemoChild = React.memo(Children);

export default function App() {
const [counter, setCounter] = React.useState(0);
const [counter2] = React.useState(0);
return (
<div className="App">
<p>counter value = {counter} </p>
<button onClick={(e) => setCounter((c) => c + 1)}>increment</button>
<MemoChild counter2={counter2} />
{/* <Children counter2={counter2} /> */}
</div>
);
}

有关 docs 中的 React.memo 的更多信息

If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.

关于javascript - 为什么当 props 没有改变时 React 会重新渲染子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67363435/

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