[英]Second arugument of React.memo() not working properly in react native
我正在尝试仅在使用React.memo()
这样的分钟更改时重新渲染:
function getCurrentTime(){
let now = new Date();
return ({
'mins': now.getMinutes(),
'secs': now.getSeconds()
})
}
const Disp = React.memo(({ timeObj }) => { //this Component is suppose to be in another file
return (<Text>{timeObj['mins']}</Text>);
}, (prevProp, newProp) => {
if (prevProp['mins'] == newProp['mins'])
return false;
return true;
});
export default function App() {
const [CurrentTime, setCurrentTime] = useState(() => getCurrentTime());
useEffect(() => {
let secTimer = setInterval(() => {setCurrentTime(getCurrentTime())}, 500);
return () => { clearInterval(secTimer) };
}, []);
return (
<View style={styles.body}>
<Disp timeObj={CurrentTime} />
</View>
);
}
但由于某种原因它不工作并每 500 毫秒渲染一次
我已经按照本教程
在比较函数中,您的返回值向后。 从文档(在代码示例的注释中):
如果将 nextProps 传递给 render 将返回与传递 prevProps 以渲染相同的结果,则返回 true,否则返回 false
您正在做相反的事情,当分钟相同时返回false
。
此外,您错过了timeObj
部分(感谢 Felix!),它应该是prevProps.timeObj.mins
(对于newProps
)。 (另外,“props”应该是复数形式,通常最好写成.mins
而不是['mins']
。)
反而:
const Disp = React.memo(
({ timeObj }) => { //this Component is supposed to be in another file
return (<Text>{timeObj.mins}</Text>);
},
(prevProps, newProps) => {
// Return true if the props are the same for rendering purposes,
// false if they aren't
return prevProps.timeObj.mins == newProps.timeObj.mins;
}
);
作为旁注,如果您想要的只是timeObj
的mins
,则可以使用嵌套解构(您可以在组件和比较函数中执行此操作,但我可能只在组件中执行此操作,重命名时会感到困惑)需要):
const Disp = React.memo(
({ timeObj: { mins } }) => { //this Component is supposed to be in another file
return (<Text>{mins}</Text>);
},
(prevProps, newProps) => {
// Return true if the props are the same for rendering purposes,
// false if they aren't
return prevProps.timeObj.mins == newProps.timeObj.mins;
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.