提问人:Coding Ninja123211 提问时间:11/14/2023 更新时间:11/14/2023 访问量:23
React memo - 自定义相等函数逻辑
React memo - custom equality function logic
问:
我有一个这样的组件:ChatMessage
const ChatMessage = memo(({messageObj, replyTo, newChatData, storedUsers, handleDeleteMessage, chatId,
}, arePropsEqual)
messageObj
是一个简单的 JavaScript 对象,如下所示: .{id: 3, text: "test"}
相等函数按预期工作,除非 Message 对象值实际更改,否则不会重新呈现。arePropsEqual
ChatMessage
相等函数:
function arePropsEqual(oldProps, newProps) {
// Logs true as expected
console.log(JSON.stringify(oldProps.messageObj) === JSON.stringify(newProps.messageObj));
return JSON.stringify(oldProps.messageObj) === JSON.stringify(newProps.messageObj)
}
以前我使用了这个相等函数,它并没有阻止预期的重新渲染:
function arePropsEqual(oldProps, newProps) {
return oldProps.messageObj === newProps.messageObj
}
此相等函数仅在将 .为什么需要 JSON.stringify?为什么这可以解决比较纯 javascript 对象的问题?谢谢。JSON.stringify
messageObj
答: 暂无答案
评论
===
===
===
===