为什么要求总是返回带有新内部引用的新对象 [英] Why is the requirement to always return new object with new internal references

查看:32
本文介绍了为什么要求总是返回带有新内部引用的新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Redux 要求总是从减速器返回新状态.例如,我有以下状态:

Redux requires that one always returns new state from reducers. For example, I have the following state:

let initialState = {
   prop: 3,
   internalReferenceProp: {a:3}
}

以及修改internalReferenceProp的reducer.这个reducer可以被实现为只改变state对象引用或同时改变stateinternalProperty:

And the reducer that modifies internalReferenceProp. This reducer can be implemented to change only state object reference or both state and internalProperty:

function(state=initialState, action) {
  // changing only state reference
  let newState = Object.assign({}, state);
  newState.internalReferenceProp.a = 7;
  return newState;

  // changing both state and internalReferenceProp reference
  return Object.assign({}, state, {internalReferenceProp: {a:7}})
}

有人告诉我第一种方法是不正确的,所以我的问题是要求也更改内部引用的原因是什么?我知道我应该更改 state 引用,因为它允许轻松比较以检测 state 是否更改,但为什么要更改内部引用?

As I've been told first approach is not correct, so my question is what's the reasoning behind requirement to also change internal references? I understand that I should change state reference because it allows for an easy comparison to detect whether state changed, but why change internal references?

推荐答案

第一个显然不正确,因为 Object.assign 是浅拷贝,而不是深拷贝.

The first one is clearly not correct because Object.assign does a shallow copy, not a deep one.

// changing only state reference
let newState = Object.assign({}, state);

newState === state // false
newState.internalReferenceProp === state.internalReferenceProp // true

state.internalReferenceProp.a // 3
newState.internalReferenceProp.a = 7 // 7
state.internalReferenceProp.a // 7

你可以这样看到,如果我们在 newState 中更改某些内容,它也会在 state 中更改.如果组件只对 internalReferenceProp 感兴趣,这将使更改无法检测.这也称为副作用",是一种不好的做法.

You can see that this way, if we change something in newState it gets changed in state as well. This will make the change undetectable if a component is only interested in internalReferenceProp. This is also called a "side-effect" and is a bad practice.

简而言之,如果您的输入(在本例中为state)以任何方式发生变化,则称为副作用并且在 redux 中是错误的.

In short, if your input (state in this case) changes in any way, it's called a side-effect and is wrong in redux.

这里有一个例子说明为什么这很糟糕:

Here's an example of why this is bad:

let data = getData(); // from redux

return (
  <ChildComponent someProp={data.internalReferenceProp} />
);

如果我们使用有副作用的版本,ChildComponent 将永远不会重新渲染,因为它的 props 没有改变.oldData.internalReferenceProp === newData.internalReferenceProp.

If we use the version with side-effects, ChildComponent will never re-render because its props didn't change. oldData.internalReferenceProp === newData.internalReferenceProp.

这篇关于为什么要求总是返回带有新内部引用的新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆