【问题标题】:The type of dispatch in typescript打字稿中的调度类型
【发布时间】:2021-03-01 08:19:32
【问题描述】:

因为我想在打字稿中我们应该尽可能避免使用“任何”类型,所以我正在重写所有的任何类型以将它们转换为更精确的类型,但是当我尝试更改类型“任何”时我遇到了问题'react redux 的 dispatch 函数。不知道用什么代替?

themeActions.ts :

export const SWITCH_THEME: string = "SWITCH_THEME";

export const switchTheme = (theme: string) => {

    return (dispatch: any) => {
        
        dispatch({ type: SWITCH_THEME, theme: theme })
        localStorage.setItem('theme', theme);

    }

}

themeReducer.ts :

import {SWITCH_THEME} from './themeActions';

const initialState = {
    theme: localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'
}

const themeReducer = (state = initialState, action: {type: string, theme: string}) => {
    switch (action.type) {
        case SWITCH_THEME:
            return {
                ...state,
                theme: action.theme
            }
            default:
                return state
    }
}

export default themeReducer;

【问题讨论】:

  • 好吧,看看你是如何使用它的。您正在调用它,所以也许是函数类型?然后想想参数和返回类型。
  • 我在themeActions.ts中用“return (dispatch: Function) =>”替换了,当你说返回类型和参数时,代码也是有效的你是什么意思?对于参数,它们在 themeActions 中可见,所以没关系 {type: SWITCH_THEME, theme: theme}?

标签: reactjs typescript redux react-redux


【解决方案1】:

只需使用import { Dispatch } from 'redux'

export const switchTheme = (theme: string) => {

    return (dispatch: Dispatch) => {
        
        dispatch({ type: SWITCH_THEME, theme: theme })
        localStorage.setItem('theme', theme);

    }

}

【讨论】:

  • redux-thunk 用户请注意:您需要 import { ThunkDispatch } from 'redux-thunk',因为 redux 中 Dispatch 的标准定义不支持 thunk。
  • @Linda Paiste 一如既往的好!
猜你喜欢
  • 1970-01-01
  • 2015-09-14
  • 2021-11-26
  • 2020-10-12
  • 2021-06-03
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
相关资源
最近更新 更多