如何解决使用 React.memo、useCallback、useMemo 防止对象重新渲染
防止原始值的重新渲染工作正常(React.memo)但是当我尝试将对象传递给子组件时问题就开始了。我尝试使用 useMemo 和 useCallback 但没有成功。 唯一的解决方案是使用 JSON.srtingify() 传递数据,然后在子组件中使用 JSON.parse() - 但这个解决方案看起来很糟糕。
import React,{useState} from 'react';
const TextExample1 = ({name,surname,infoText}) => {
console.log(infoText);
return (
<p>
{infoText} {name} {surname}
</p>
);
};
const TextExample2 = React.memo(({name,infoText}) => {
console.log(infoText);
return (
<p>
{infoText} {name} {surname}
</p>
);
});
const TextExample3 = React.memo(({data,infoText}) => {
console.log(infoText);
return (
<p>
{infoText} {data.name} {data.surname}
</p>
);
});
const TextExample4 = React.memo(({data,infoText}) => {
console.log(infoText);
const parsedData = JSON.parse(data);
return (
<p>
{infoText} {parsedData.name} {parsedData.surname}
</p>
);
});
const App = () => {
console.log('----- NEW RENDER -----');
const [forceRerenderNumber,setForceRerenderNumber] = useState(0);
const sourceData = {
name: 'Joe',surname: 'Moore',};
return (
<div>
<TextExample1
name="Joe"
surname="Moore"
infoText="1 - Works fine - intented rerenders :)"
/>
<TextExample2
name="Joe"
surname="Moore"
infoText="2 - Works fine - intented no rerenders. Rendered only onece :)"
/>
<TextExample3
data={sourceData}
infoText="3 - Doesn't work fine - there are unintented rerendars :( How to stop it?"
/>
<TextExample4
data={JSON.stringify(sourceData)}
infoText="4 - Works. - intented no rerenders. But JSON.stringify() and JSON.parse() looks like really hacky way. How to improve it?"
/>
<Button
onClick={() => {
setForceRerenderNumber(forceRerenderNumber + 1);
}}>
Rerender
</Button>
</div>
);
};
export default App;
日志:
LOG ----- NEW RENDER -----
LOG 1 - Works fine - intented rerenders :)
LOG 2 - Works fine - intented no rerenders with primitive data. Rendered only onece :)
LOG 3 - Doesn't work fine - there are unintented rerendars :( How to stop it?
LOG 4 - Works. - intented no rerenders. But JSON.stringify() and JSON.parse() looks like really hacky way. How to improve it?
LOG ----- NEW RENDER -----
LOG 1 - Works fine - intented rerenders :)
LOG 3 - Doesn't work fine - there are unintented rerendars :( How to stop it?
LOG ----- NEW RENDER -----
LOG 1 - Works fine - intented rerenders :)
LOG 3 - Doesn't work fine - there are unintented rerendars :( How to stop it?
解决方法
如果 Find
是一个不变的常量,你可以把它放在组件之外:
sourceData
如果const sourceData = {
name: "Joe",surname: "Moore",};
const App = () => {}
可以改变,你可以使用sourceData
:
useMemo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。