freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/redux/copy-an-object-with-object....

3.6 KiB

id title challengeType isRequired videoUrl localeTitle
5a24c314108439a4d403615b Copy an Object with Object.assign 6 false 使用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

tests:
  - text: Redux存储应该存在并使用等效于第1行声明的<code>defaultState</code>对象的状态进行初始化。
    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 <code>defaultState</code> object declared on line 1.");'
  - text: <code>wakeUp</code>和<code>immutableReducer</code>都应该是函数。
    testString: 'assert(typeof wakeUp === "function" && typeof immutableReducer === "function", "<code>wakeUp</code> and <code>immutableReducer</code> both should be functions.");'
  - text: 调度<code>ONLINE</code>类型的操作应该将<code>status</code>中的属性<code>status</code>更新为<code>online</code>并且不应该改变状态。
    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 <code>ONLINE</code> should update the property <code>status</code> in state to <code>online</code> and should NOT mutate state.");'
  - text: <code>Object.assign</code>应该用于返回新状态。
    testString: 'getUserInput => assert(getUserInput("index").includes("Object.assign"), "<code>Object.assign</code> should be used to return new state.");'

Challenge Seed

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

// solution required