我在尝试为我的 React 组件键入参数时遇到错误。我想严格输入组件的 props 和状态上的属性,但是当我使用 Redux 这样做时,当我将 mapStateToProps 传递给连接函数时出现错误。
这是组件代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import FileExplorer from '../components/file-explorer/file-explorer';
import { ISideMenu, ISideMenuState } from '../models/interfaces/side-menu';
class SideMenu extends Component<ISideMenu, ISideMenuState> {
render() {
return (
<div>
{this.props.fileExplorerInfo !== null &&
<FileExplorer fileExplorerDirectory={this.props.fileExplorerInfo.fileExplorerDirectory}/>
}
</div>
);
}
}
const mapStateToProps = (state: ISideMenuState) => {
return {
fileExplorerInfo: state.fileExplorer
};
};
export default connect<ISideMenu, null, ISideMenuState>(mapStateToProps)(SideMenu);
所以错误发生在这一行:
export default connect<ISideMenu, null, ISideMenuState>(mapStateToProps)(SideMenu);
当我将鼠标悬停在该行中的“mapStateToProps”一词上时,我看到了错误:
Argument of type '(state: ISideMenuState) => { fileExplorerInfo: FileDirectoryTree | null; }'
is not assignable to parameter of type 'MapStateToPropsParam<ISideMenu, ISideMenuState, {}>'.
Type '(state: ISideMenuState) => { fileExplorerInfo: FileDirectoryTree | null; }' is not
assignable to type 'MapStateToProps<ISideMenu, ISideMenuState, {}>'.
Types of parameters 'state' and 'state' are incompatible.
Type '{}' is not
assignable to type 'ISideMenuState'.
Property 'fileExplorer' is missing in type '{}'.
这是我在 React 组件中使用的两个接口(interface):
export interface ISideMenu {
fileExplorerInfo: FileExplorerReducerState | null;
}
export interface ISideMenuState {
fileExplorer: FileDirectoryTree | null;
}
任何对此错误的见解将不胜感激!
最佳答案
当使用泛型时,你会弄错接口(interface)的位置:
当您声明您的 React 组件时:
class Comp extends Component<ICompProps, ICompState>
ICompProps
和 ICompState
分别是组件的属性和内部状态。
当您使用连接时:
connect<IMapStateToProps, IMapDispatchToProps, ICompProps, IReduxState>
IMapStateToProps
表示您的 mapStateToProps()
函数返回的内容。
IMapDispatchToProps
表示您的 mapDispatchToProps()
函数返回的内容。
ICompProps
代表你的 React 组件 Prop (同上)
IReduxState
代表你的 App 的 Redux 状态
因此在您的特定示例中:
当声明你的 React 组件时:
class SideMenu extends Component<ISideMenu, {}>
使用 ISideMenu
作为 Prop ,使用 {}
(空状态)作为状态,因为您不使用任何状态。
使用连接时:
connect<ISideMenu, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);
您可以使用 ISideMenu
作为 React 组件 Prop 和 mapStateToProps
返回的对象。但在实践中,最好创建 2 个单独的接口(interface)。
在我的应用程序中,我通常懒得输入 mapStateToProps
返回对象,所以我只使用:
connect<{}, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);
关于javascript - 使用 typescript 强类型化 react-redux connect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292707/