【问题标题】:How do I update the state on an object without changing the properties that do not have a new value?如何在不更改没有新值的属性的情况下更新对象的状态?
【发布时间】:2018-08-29 17:24:00
【问题描述】:

我有这个减速器。

case UPDATE_ENDPOINT:
  return <IState>state.map(endpoint =>
    endpoint.ocid === action.endpoint.ocid
      ? { 
        ...endpoint, 
        name: action.endpoint.name,
        hostname: action.endpoint.hostname,
        origin: action.endpoint.origin,
        originType: action.endpoint.originType,
        originValidation: action.endpoint.originValidation,
      }
      : endpoint
  );

假设在我的action payload中我只有endpoint.nameendpoint.hostname,那么reducer会将payload中没有传入的值设置为undefined。如何让reducer 只更新action payload 中的值,而让不在action payload 中的值保持不变?

【问题讨论】:

    标签: javascript redux reducers redux-actions


    【解决方案1】:

    最简单的方法是使用对象传播语法:

    case UPDATE_ENDPOINT:
      return <IState>state.map(endpoint =>
        endpoint.ocid === action.endpoint.ocid
          ? { 
            ...endpoint, 
            ...action.endpoint
          }
          : endpoint
      );
    

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 2021-08-06
      • 1970-01-01
      • 2020-02-01
      • 2017-08-07
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多