对 Redux 状态副本进行更改也会更新 Redux 存储上的实际状态
我看到这种行为,如果我将 redux 状态复制到局部变量并更改该变量,它也会更新我的 redux 存储,而无需我使用任何类型的调度,这是我的代码:
// here is my action type inside my reducer
case SET_USERS:
return {
...state,
users: action.payload,
};
// and here i have a helper function to select a specific state and pass it to useSelector later on
export const getUsersSelector = (state: RootState) => {
return state.app.users;
};
并且我正在像这样访问我的状态在我拥有的自定义钩子 useUsers
内
export const useUsers = () => {
const users = useSelector(getUsersSelector);
return {users}
}
,我正在使用 useUsers
钩子访问另一个组件中的 users
值:
const ListUsers = () => {
const {users} = useUsers()
//i make a copy of my users state
const copyOfUsers = users
//and update the copied variable
copyOfUsers.push({name: 'John'})
retunr (<View>{copyOfUsers.map((user)=><Text>{user.name}</Text>)}</View>)
}
我遇到的问题是推送我的新物品copyOfUsers
变量还会更新 redux 存储中的 user
状态,我不知道为什么会发生这种情况,以及它是否是正常行为,只是想知道这是否是一个错误或redux 的故意行为?或者我怎样才能避免它?
I am seeing this behaviour where if i copy a redux state to a local variable and make a change to that variable it also updates my redux store without me using any kind of dispatching, here is my code:
// here is my action type inside my reducer
case SET_USERS:
return {
...state,
users: action.payload,
};
// and here i have a helper function to select a specific state and pass it to useSelector later on
export const getUsersSelector = (state: RootState) => {
return state.app.users;
};
and i am accessing my state like this inside a custom hook useUsers
i have
export const useUsers = () => {
const users = useSelector(getUsersSelector);
return {users}
}
and i am accessing my users
value in another component using the useUsers
hook:
const ListUsers = () => {
const {users} = useUsers()
//i make a copy of my users state
const copyOfUsers = users
//and update the copied variable
copyOfUsers.push({name: 'John'})
retunr (<View>{copyOfUsers.map((user)=><Text>{user.name}</Text>)}</View>)
}
the issue i am having is pushing a new item to my copyOfUsers
variable also updates the users
state inside the redux store, i dont know why this is happening and if its a normal behaviour, just wanted to know if this is a bug or intentional behaviour of redux? or how i can avoid it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上是在更改
users
实例的浅拷贝
。您应该首先创建
users
实例的深层副本
,然后对数据进行操作。users 是一个
Array
,因此,您可以使用slice
创建深层副本,然后应将新对象推送到用户的新副本中。这将阻止你的 redux 副本中反映突变。您的代码应如下所示:
You are actually altering
shallow copy
of theusers
instance.You should first create a
deep copy
of theusers
instance and then operate on the data.The users is an
Array
so, you could have usedslice
to create a deep copy and then should have pushed the new object in the new copy of the users. That would have prevented the reflection of mutation in your redux copy.Your code should look like: