在应用程序中使用redux,存储在javascript模块中定义,并在typescript模块中使用



我继承了一个具有JavaScript模块和TypeScript模块的应用程序,并且正在使用redux
不幸的是,我从未使用过TypeScript:(

  • 状态是在.js模块中定义的
  • 所有使用该状态的模块也是.js模块
  • 现在我需要访问一个.ts模块中的状态

我该怎么做?

这是我在一个名为uiReducer.js:的文件中的状态定义

export default function uiReducer(state = new UiState, action) {
switch(action.type) {
...

它被用于多个.js模块中,如以下示例所示:

const mapStateToProps = state => {
return {
a: state.get('ui').get('a'),
b: state.get('ui').get('b')
}
}
const mapDispatchToProps = dispatch => {
return {
...
}
}
export var About =
connect(mapStateToProps, mapDispatchToProps)(About_Class);

正如我在上面所写的,我想在.ts模块中使用它。你能告诉我我是怎么做的吗

我无法提供对源代码的完全访问权限,因为我不拥有它。但我可以添加所需的信息。

我假设您使用的是类组件,所以我提供的解决方案就是这样。

第一步是导入ConnectedProps:

import { connect, ConnectedProps } from 'react-redux'

下一步是定义您的状态/减少器的对象,因此在一个我们可以命名为TsConnector.ts的文件中,添加一些类似的内容:

interface UIState {
a: string,
b: string,
...your other props
}
interface State {
UI: UI,
...your other props
}

然后创建mapStatemapDispatch函数:

const mapState = (state: UIState ) => ({
UI: state.UI,
...your other props
})
const mapDispatch = {
... your dispatch action
}

和出口:

export default tsconnector = connect(mapState, mapDispatch)

然后像通常使用HOC组件一样使用它:

import { tsconnector } from '../components/TsConnector'
export var About =
tsconnector(mapStateToProps, mapDispatchToProps)(About_Class);

就是这样。

您是否尝试过ts文件中的useDispatchuseSelector来获得冗余状态

import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'

export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector

最新更新