假设我有一个状态如下的减速器:
messages: [
{
"id": "94",
"characterId": "1",
"text": "Uhm... Who are you?",
"cloneId": "",
"parentId": ""
},
{
"id": "92",
"characterId": "1",
"text": "So what's with the whole E=mc2 thing?",
"cloneId": "",
"parentId": ""
},
{
"id": "68-1",
"characterId": "1",
"text": "Oh no. Even now, we only have a small glimpse of the bottom of the ocean!",
"cloneId": "",
"parentId": "68"
}
]
如何让Message组件表示id为"92"的消息?只渲染id为"92"的对象更新?
这种方法在数组中的任何对象发生变化时都会导致渲染:/
const Message = () => {
const data = useSelector((state) => state.conversationsData.messages.find((m) => {
return m.id == '92'
}))
...
}
redux在文档中给出了这个问题的一些解决方案。您可以传递shallowEqual
(或其他您喜欢的比较方法)作为第二个参数,如:
import { shallowEqual, useSelector } from 'react-redux'
const Message = () => {
const data = useSelector((state) => state.conversationsData.messages.find((m) => {
return m.id == '92'
}), shallowEqual)
...
}
对于更复杂的记忆情况,您可以使用redux和reselect library进行记忆。
你可以使用"useEffect">
const [refresh, setRefresh] = useState(false)
useEffect(() => {
if (//check for particular message variable changes) {
setRefresh(refresh=>!refresh)
}
}, [messages])
<MessageComponent refresh={refresh} />
使用这种方法,消息组件将只在刷新更改值
时呈现