我在尝试为我的react组件键入参数时遇到错误。我想简单地输入组件的属性和状态上的属性,但是当我使用Redux进行操作时,将mapStateToProps传递给connect函数时出现错误。
这是组件代码:
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组件中使用的两个接口:
export interface ISideMenu { fileExplorerInfo: FileExplorerReducerState | null; } export interface ISideMenuState { fileExplorer: FileDirectoryTree | null; }
任何对此错误的见解将不胜感激!
当使用泛型时,您会发现错误的接口位置:
声明React组件时:
class Comp extends Component<ICompProps, ICompState>
随着ICompProps和ICompState分别为您的组件的道具和内部状态。
ICompProps
ICompState
使用connect时:
connect<IMapStateToProps, IMapDispatchToProps, ICompProps, IReduxState>
IMapStateToProps表示mapStateToProps()函数返回的内容。 IMapDispatchToProps表示mapDispatchToProps()函数返回的内容。 ICompProps代表您的React组件道具(与上面相同) IReduxState代表您的应用程序的Redux状态
IMapStateToProps
mapStateToProps()
IMapDispatchToProps
mapDispatchToProps()
IReduxState
因此,在您的特定示例中:
在声明您的React组件时:
class SideMenu extends Component<ISideMenu, {}>
使用ISideMenu的道具和{}(空状态)的状态,你不使用任何状态。
ISideMenu
{}
使用连接时:
connect<ISideMenu, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);
您既可以ISideMenu用作React组件的prop,也可以用作所返回的对象mapStateToProps。但实际上,最好创建两个单独的接口。
mapStateToProps
在我的应用中,通常不必打扰键入mapStateToProps返回对象,因此我只需使用:
connect<{}, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);