我有一个 Web 应用程序从 websocket 接收更新,例如每秒 100 条消息。
我正在使用不可变助手并尝试了这个
const parentIndex = action.payload.data.findIndex( i => i.id===action.id)
if(parentIndex !== -1) {
const childIndex = action.payload.data[parentIndex].child.findIndex(c=>i.id===action.childId)
if(child !== -1) {
const lastChildIndex = action.payload.data[parentIndex].child[childIndex].lastChild.findIndex(l=>l.id===action.lastChildId)
return lastChildIndex=== -1
? update(state, { // insert
data: {
[parentIndex]: {
child: {
[childIndex]: {
lastChild: {
$push: [{
parentId: action.id,
childId: action.childId,
lastChildId: action.lastChildId,
price: action.payload.price
}]
}
}
}
}
}
})
: update(state, { // update
data: {
[parentIndex]: {
child: {
[childIndex]: {
lastChild: {
[lastChildIndex]:{
price: { $set: action.payload.price},
isUpdated: { $set: true}
}
}
}
}
}
}
})
}
}
示例数据:
data = [
{
parentId: 123,
itemName: 'John Doe',
child: {
childId: 456,
childName: 'I am child one',
lastChild: {
lastChildId: 789,
price: 143
}
}
},
{
parentId: 321,
itemName: 'John Wick',
child: {
childId: 654,
childName: 'I am child wick',
lastChild: {
lastChildId: 987,
price: 44
}
}
}
]
这似乎至少适用于 5 个数据数组,但是当数据超过 15 个时,浏览器似乎很慢,内存泄漏,很快就崩溃了..
每次有消息推送到应用程序时查找索引 将杀死浏览器。
我使用 redux-thunk 作为中间件。
如果你能给我推荐一些可以更快、更好、无缝更新/插入的东西。那真是太酷了。
最佳答案
首先解决这个问题:
a web application that received an update from websocket, like 100 messages per second
你应该throttle或者对它们进行反跳,这样您就不会更新每条消息的状态。或者如果可以的话,减少消息数量。或者两者兼而有之。
一旦你解决了这个问题,应用程序应该可以正常工作。但您仍然可以做出一些改进:
鉴于此操作:
{
payload: {
parentId: 123,
childId: 321,
lastChildId: 555,
price: 50
}
}
你的 reducer 将如下所示:
const { parentId, childId, lastChildId } = action.payload;
const childItem = state[parentId][childId][lastChildId];
const newState = {...state}
newState[parentId][childId][lastChildId] = {...childItem, ...action.payload};
return newState;
如果我知道我需要像您在这里所做的那样查找特定项目,我会选择 map 而不是数组。
关于reactjs - 优化更新 redux 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448467/