在 redux 中实现 reselect 可以防止新的更改立即出现
Implementing reselect in redux prevents new changes to appear instantly
在我的 React 项目中,我使用 reselect 库实现了记忆。
状态基本上有一个对象列表,我将其呈现为卡片。
在实施重新选择之前,每当我添加一个新元素时,更改会立即显示出来,最后会添加一张新卡片。但是,现在当我添加一个新元素时,它不会立即显示,而是在重新加载页面时显示。
为什么会这样?有没有办法在不删除重新选择库
的情况下解决这个问题
编辑:问题已经解决,正如答案中指出的那样,这是因为我只是在改变状态
之前的代码如下
case IssueActionTypes.ADD_ISSUE:
state.issueList.push(action.payload)
return {
...state
}
我用
替换了
case IssueActionTypes.ADD_ISSUE:
return {
...state,
issueList : [...state.issueList, action.payload]
}
解决了问题
很可能您在 reducer 中返回了变异的状态,而不是返回一个新数组。
Docs:
createSelector uses an identity check (===) to detect that an input
has changed, so mutating an existing object will not trigger the
selector to recompute because mutating an object does not change its
identity. Note that if you are using Redux, mutating the state object
is almost certainly a mistake.
返回变异状态的示例(来自文档):
export default function todos(state = initialState, action) {
switch (action.type) {
case COMPLETE_ALL:
const areAllMarked = state.every(todo => todo.completed)
// BAD: mutating an existing object
return state.map(todo => {
todo.completed = !areAllMarked
return todo
})
default:
return state
}
}
在我的 React 项目中,我使用 reselect 库实现了记忆。 状态基本上有一个对象列表,我将其呈现为卡片。
在实施重新选择之前,每当我添加一个新元素时,更改会立即显示出来,最后会添加一张新卡片。但是,现在当我添加一个新元素时,它不会立即显示,而是在重新加载页面时显示。
为什么会这样?有没有办法在不删除重新选择库
的情况下解决这个问题编辑:问题已经解决,正如答案中指出的那样,这是因为我只是在改变状态
之前的代码如下
case IssueActionTypes.ADD_ISSUE:
state.issueList.push(action.payload)
return {
...state
}
我用
替换了case IssueActionTypes.ADD_ISSUE:
return {
...state,
issueList : [...state.issueList, action.payload]
}
解决了问题
很可能您在 reducer 中返回了变异的状态,而不是返回一个新数组。
Docs:
createSelector uses an identity check (===) to detect that an input has changed, so mutating an existing object will not trigger the selector to recompute because mutating an object does not change its identity. Note that if you are using Redux, mutating the state object is almost certainly a mistake.
返回变异状态的示例(来自文档):
export default function todos(state = initialState, action) { switch (action.type) { case COMPLETE_ALL: const areAllMarked = state.every(todo => todo.completed) // BAD: mutating an existing object return state.map(todo => { todo.completed = !areAllMarked return todo }) default: return state } }