[英]How to avoid re-rendering when i pass an object as prop to child component?
我有多個子組件的父組件。 從 api 獲取數據后,會向子組件傳遞不同類型的數據。 一些組件將對象作為道具。 我試圖避免在該組件中重新渲染。 即使數據相同,它也會重新渲染。 我怎樣才能避免這種重新渲染?
const Parent = () => {
const [childData, setChildData] = useState(null);
useEffect(() => {
const data = getChildData();
setChildData(data);
}, [])
return (
<Child data={childData}/>
);
};
const Child = React.memo((props) => {
const {name, email} = props.data;
return (
<div>
<p>Name: {name}</p>
<p>Email: {email}</p>
</div>
);
});
根據 React 官方文檔,默認情況下,React 只會淺比較 props 對象中的復雜對象。 如果您想控制比較,您還可以提供自定義比較函數作為第二個參數。 https://reactjs.org/docs/react-api.html#reactmemo 。 這是一個例子。
const Parent = () => {
const [childData, setChildData] = useState(null);
useEffect(() => {
const data = getChildData();
setChildData(data);
}, [])
return (
<Child data={childData} />
);
};
function areEqual(prevProps, nextProps) {
return prevProps.name == nextProps.name && prevProps.email == nextProps.email;
}
const Child = React.memo((props) => {
const { name, email } = props.data;
return (
<div>
<p>Name: {name}</p>
<p>Email: {email}</p>
</div>
);
}, areEqual);
默認情況下React.memo只會shallowly compare
props
復雜對象。
您可以使用props 的自定義相等性檢查。 將自定義檢查函數作為第二個參數傳遞給React.memo
類似於下面
const areEqual = (prevProps, nextProps) => {
const {name, email} = prevProps.data;
const {name: nextName, email: nextEmail} = nextProps.data;
return name === nextName && email === nextEmail;
};
const Child = React.memo((props) => {...}, areEqual);
有關更多詳細信息,請查看此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.