我正在嘗試僅在分鐘更改時重新渲染,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 毫秒渲染一次
我已經按照本教程進行了操作
uj5u.com熱心網友回復:
在比較函式中,您的回傳值向后。從檔案(在代碼示例的注釋中):
如果將 nextProps 傳遞給 render 將回傳與傳遞 prevProps 以渲染相同的結果,則回傳 true,否則回傳 false
你正在做相反的事情,false當分鐘相同時回傳。
此外,您錯過了timeObj部分(感謝 Felix!),它應該是prevProps.timeObj.mins(對于newProps)。(此外,“道具”應該是復數形式,通常最好寫成.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;
}
);
作為旁注,如果您想要的只是minsfrom ,您可以使用嵌套解構timeObj(您可以在組件和比較函式中執行此操作,但我可能只在組件中執行此操作,在進行所需的重命名時會感到困惑) :
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;
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/334697.html
標籤:javascript 反应 反应原生
上一篇:如何在react-native中顯示來自Pressable的泛化功能
下一篇:如何在回應中獲取多個ID的索引
