gpt4 book ai didi

javascript - 使用 typescript 强类型化 react-redux connect

转载 作者:可可西里 更新时间:2023-11-01 01:47:52 24 4
gpt4 key购买 nike

我在尝试为我的 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>

ICompPropsICompState 分别是组件的属性和内部状态。

当您使用连接时:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com