【问题标题】:Flow Type Check: How to iterate on possibly undefined property in redux action?流类型检查:如何在 redux 操作中迭代可能未定义的属性?
【发布时间】:2017-08-28 09:15:04
【问题描述】:

我有一个用于偏好设置的 Redux reducer,并且我正在使用 Flow Type Checker。我的 reducer 可以采取两种类型的操作。一种用于加载在初始应用程序加载时发生的所有首选项。第二种操作类型发生在用户更新特定偏好时。这是我的减速器的代码。我遇到问题的地方是当我尝试执行 action.prefs.forEach 时,流程会抛出一个错误,提示 ...'prefs': Property not found in 'object type'

// @flow
import {
  UPDATE_PREF,
  LOAD_PREFS_SUCCESS
} from '../actions/prefs';

export type actionType = {
  +type: string,
  prefs: Array<{_id: string, value: any}>
} | {
  +type: string,
  id: string,
  value: any
};

export default (state: stateType = {}, action: actionType) => {
  switch (action.type) {
    case LOAD_PREFS_SUCCESS: {
      const newState = {};
      action.prefs.forEach(p => {
        newState[p._id] = p.value;
      });
      return newState;
    }
    case UPDATE_PREF: {
      return { ...state, [action.id]: action.value };
    }
    default:
      return state;
  }
};

如您所见,我有两种类型的操作。加载所有首选项时,该操作具有一组首选项。 [ { _id: 'color', value: 'blue' } ] 当更新一个偏好时,我得到一个 id 和一个值。那么给我的两个具有不同属性的动作类型,我如何让流不引发关于动作流类型的这种变化的错误?

【问题讨论】:

    标签: redux flowtype


    【解决方案1】:

    为了告诉 Flow 在 disjoint union 中选择哪种类型,+type 必须是一个值,而不是 string。将您的 actionType 更改为使用值:

    // @flow
    import {
      UPDATE_PREF,
      LOAD_PREFS_SUCCESS
    } from '../actions/prefs';
    
    export type actionType = {
      +type: LOAD_PREFS_SUCCESS, // not just `string`
      prefs: Array<{_id: string, value: any}>
    } | {
      +type: UPDATE_PREF,        // not just `string`
      id: string,
      value: any
    };
    

    【讨论】:

    • 谢谢罗斯。不幸的是,这似乎并没有消除错误。
    • @yourfavorite 除了上面的改动,试试我stackoverflow.com/a/44640430/368697的回答
    • 我无法弄清楚你的例子的哪一部分可以解决这个问题,但我想出了如何解决 flow.org/try 上的错误,这要感谢你的例子。我创建了一个没有错误的流程,但现在的问题是,当状态的另一部分的操作被触发时,它会导致 TypeError,因为它与我的两个 actionType 中的任何一个都不匹配。我将为此创建一个新的 SO Question,因为它是一个不同的问题。我正在用该解决方案创建一个新的答案,希望它能在未来帮助其他人。感谢您的帮助!
    【解决方案2】:

    感谢 @ross-allen 的一些指导和一些在 flow.org 上的玩弄,我找到了 working solution

    简而言之,除了Ross 的答案加+type: UPDATE_PREF,我还需要加typeof。所以工作的actionType是:

    export type actionType = {
      +type: typeof LOAD_PREFS_SUCCESS,
      prefs: Array<{_id: string, value: any}>
    } | {
      +type: typeof UPDATE_PREF,
      id: string,
      value: any
    };
    

    再次感谢@ross-allen。

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2022-01-03
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 2018-02-04
      相关资源
      最近更新 更多