【发布时间】: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