Jestjs 国家混乱

Jestjs 国家混乱,jestjs,reducers,state-management,Jestjs,Reducers,State Management,此代码适用于: const defaultState = { myProp: false }; it('should change the value of myProp', () => { let state = defaultState; console.log(state); state.myProp = true; console.log(state) }); 如人们所料,myProp已成功更改为true 但这似乎不起作用: const myReducer

此代码适用于:

const defaultState = {
  myProp: false
};

it('should change the value of myProp', () => {
  let state = defaultState;

  console.log(state);
  state.myProp = true;
  console.log(state)
});
如人们所料,
myProp
已成功更改为
true

但这似乎不起作用:

const myReducer = (state, action) => {
  switch(action.type) {
    case CHANGE_PROP: {
      return {
        ...state,
        myProp: action.myProp
      };
    }
  }
};

const defaultState = {
  myProp: false
};

it('should change the value of myProp', () => {
  let state = defaultState;

  console.log(state);
  myReducer(state, {type: types.CHANGE_PROP, myProp: true});
  console.log(state)
});
我已经简化了这个帖子的代码,但是核心代码在那里。简单地说,
state.myProp
不会改变

然而,这是可行的:

expect(
  myReducer(state, {type: types.CHANGE_PROP, myProp: true})
).toEqual(
  {
    ...state,
    myProp: true
  }
);

因此,在我的单元测试中,为什么我不能更改
myProp
值并使其保持不变?

我想我知道我在哪里困惑了

我可以用这种方法解决这个问题

let newState = myReducer(state, {type: types.CHANGE_PROP, myProp: true});
而且
newState.myProp
肯定是
true

我的困惑是,我假设
state
是通过引用传递的,所以我认为更新它的属性会级联回调用它的位置。显然不是

在我的上下文中,使用此减速器的是:

const [state, dispatch] = useReducer(myReducer, defaultState);
因此,我可以推断由
myReducer
更新的状态道具将
state
的新实例返回到上下文。至少这是我的假设