--- id: 5a24c314108439a4d403615b title: Copy an Object with Object.assign challengeType: 6 isRequired: false videoUrl: '' localeTitle: 使用Object.assign复制对象 --- ## Description
最后几个挑战适用于数组,但是当状态是一个object时,有一些方法可以帮助强制执行状态不变性。处理对象的有用工具是Object.assign()实用程序。 Object.assign()接受目标对象和源对象,并将源对象中的属性映射到目标对象。任何匹配的属性都会被源对象中的属性覆盖。此行为通常用于通过将空对象作为第一个参数传递,然后传递要复制的对象来生成对象的浅副本。这是一个例子: const newObject = Object.assign({}, obj1, obj2);这将newObject创建为一个新object ,其中包含当前存在于obj1obj2中的属性。
## Instructions
Redux状态和操作被修改为处理stateobject 。编辑代码以返回类型为ONLINE操作的新state对象,该status属性将status属性设置为online字符串。尝试使用Object.assign()来完成挑战。
## Tests
```yml tests: - text: Redux存储应该存在并使用等效于第1行声明的defaultState对象的状态进行初始化。 testString: 'assert((function() { const expectedState = { user: "CamperBot", status: "offline", friends: "732,982", community: "freeCodeCamp" }; const initialState = store.getState(); return DeepEqual(expectedState, initialState); })(), "The Redux store should exist and initialize with a state that is equivalent to the defaultState object declared on line 1.");' - text: wakeUpimmutableReducer都应该是函数。 testString: 'assert(typeof wakeUp === "function" && typeof immutableReducer === "function", "wakeUp and immutableReducer both should be functions.");' - text: 调度ONLINE类型的操作应该将status中的属性status更新为online并且不应该改变状态。 testString: 'assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch({type: "ONLINE"}); const finalState = store.getState(); const expectedState = { user: "CamperBot", status: "online", friends: "732,982", community: "freeCodeCamp" }; return isFrozen && DeepEqual(finalState, expectedState); })(), "Dispatching an action of type ONLINE should update the property status in state to online and should NOT mutate state.");' - text: Object.assign应该用于返回新状态。 testString: 'getUserInput => assert(getUserInput("index").includes("Object.assign"), "Object.assign should be used to return new state.");' ```
## Challenge Seed
```jsx const defaultState = { user: 'CamperBot', status: 'offline', friends: '732,982', community: 'freeCodeCamp' }; const immutableReducer = (state = defaultState, action) => { switch(action.type) { case 'ONLINE': // don't mutate state here or the tests will fail return default: return state; } }; const wakeUp = () => { return { type: 'ONLINE' } }; const store = Redux.createStore(immutableReducer); ```
## Solution
```js // solution required ```