如果父组件在React中重新渲染,无论传递的props是否更改,子组件也会重新渲染。
为什么React这样做?如果父组件重新渲染时不重新渲染没有更改的props的子组件会有什么问题?
更新:我正在React Devtools性能分析器中谈论这个问题:
示例代码:
App.tsx:
为什么React这样做?如果父组件重新渲染时不重新渲染没有更改的props的子组件会有什么问题?
更新:我正在React Devtools性能分析器中谈论这个问题:
![enter image description here](https://istack.dev59.com/rgCYk.webp)
App.tsx:
import React, { useMemo, useState } from "react";
import "./App.css";
import { Item, MyList } from "./MyList";
function App() {
console.log("render App (=render parent)");
const [val, setVal] = useState(true);
const initialList = useMemo(() => [{ id: 1, text: "hello world" }], []); // leads to "The parent component rendered"
//const initialList: Item[] = []; // leads to "Props changed: (initialList)"
return (
<div style={{ border: "10px solid red" }}>
<button type="button" onClick={() => setVal(!val)}>
re-render parent
</button>
<MyList initialList={initialList} />
</div>
);
}
export default App;
MyList.tsx:
import { FC, useState } from "react";
export interface Item {
id: number;
text: string;
}
interface Props {
initialList: Item[];
//onItemsChanged: (newItems: Item[]) => void;
}
export const MyList: FC<Props> = ({
initialList,
//onItemsChanged,
}) => {
console.log("render MyList");
const [items, setItems] = useState(initialList);
return (
<div style={{ border: "5px solid blue" }}>
<ul>
{items.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
<button type="button">add list item (to be implemented)</button>
</div>
);
};
console.log
语句,但正如预期的那样,这并没有改变任何东西。 - stefan.at.kotlin