【问题标题】:Passing in types properly to Redux reducer将类型正确传递给 Redux reducer
【发布时间】:2017-10-18 21:38:06
【问题描述】:

我在使用 Typescript 在 Redux 中的 reducer 函数中尝试将正确的类型传递给我的 action 属性时遇到了一些困难。在常规的 es6 语法中,我会传入如下类型:

action: {}

但是在 Typescript 中是针对更具体的动作类型,所以我尝试过这样的事情:

import {
  UPDATE_STATE,
} from '../constants/ActionTypes';

import * as Actions from '../actions/index.js';

const initialState = {
  someState: '',
}

// TODO: Type checking here is throwing an error

export default function counter(state = initialState, action : Actions ) {
  switch(action.type) {
    case UPDATE_STATE:
      return {
        ...state,
      }
    }
}

当我尝试在 Webpack 中编译时,Typescript 当前抛出此错误:

[at-loader] ./src/reducers/numberpad.tsx:27:64 中的错误 TS2304:找不到名称“操作”。

动作:

index.js
import * as types from '../constants/ActionTypes'

export function update(val) {
  return { type: types.UPDATE, val }
}

常量:

export const UPDATE = 'UPDATE'

到目前为止,我很茫然,我也尝试过将类型作为“对象”传递(因为从我的操作返回的是一个实际对象)但是,这似乎也没有得到认可。我也尝试过指定“any”类型以使其更灵活,但 TS 似乎也不喜欢这样。

对于 TS 在这些情况下检查的内容,我有点困惑。任何想法都会受到欢迎。谢谢。

【问题讨论】:

  • 您能否显示您的操作/索引文件在哪里导出您的操作?我的猜测是问题在那里
  • 刚刚添加它们

标签: reactjs typescript redux reducers


【解决方案1】:

您的操作应该是一个接口或类型。

您的导入是从 index.js 文件中导入所有内容并将其命名为“Actions”。

在您的 index.js 文件中,您需要声明一个类型或接口,例如

export interface IAction {
    type: string;
    data: any;
}

那么在你的 reducer 中,你需要:

import {IAction} from '../actions/index.js';

...然后是你的减速器:

export default function counter(state = initialState, action : IAction) {
  switch(action.type) {
    case UPDATE_STATE:
      return {
        ...state,
      }
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多