[英]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.