首页 文章

redux减速机流量不推断类型

提问于
浏览
0

我在从flow docs开始基本上执行基本的redux-reducer示例时遇到了流错误 .

此处添加到代码中的流出错:在 REMOVE 开关情况下: action 未解析为正确的类型 .

如果我将鼠标悬停在vscode中的 payload 上,则在 ADD 情况下将其显示为 AddAction ,但在 REMOVE 情况下,它显示为所有操作的并集,即 Action .

我错过了什么或理解错了什么? Flow应该从 Actions union中删除正确的类型到 ifswitch 中唯一可能的类型 .

// @flow
const initialState = [];

type Item = { id: number, data: string };
type State = Item[];

type AddAction = {
  type: 'ADD',
  payload: Item
};

type RemoveAction = {
  type: 'REMOVE',
  payload: { id: number }
};

type ClearAction = {
  type: 'CLEAR'
};

type Action = AddAction | RemoveAction | ClearAction;

const reducer: (State, Action) => State = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD': {
      return [...state, action.payload];
    }

    case 'REMOVE': {
      return state.filter(t => t.id !== action.payload.id);
                                               ^ property `payload`. Property not found in
    }

    case 'CLEAR': {
      return [];
    }

    default:
      (action: empty);
      return state;
  }
};

export default reducer;

169994

1 回答

  • 3

    好吧,似乎问题是使用了 action 里面 Array.filter 箭头功能:

    如果我用 REMOVE 案例内容替换

    case 'REMOVE': {
      const id = action.payload.id;
      return state.filter(t => t.id !== id);
    }
    

    错误消失了 .

    我猜流量无法推断出箭头函数内的类型 . 知道原因会很有趣 .

    编辑:related question

    因此,flow使联合细化无效,因为它假定filter()可能对reducer参数 actiondocs)执行副作用 . 在使用之前将操作或有效负载存储在const中 .

相关问题