首页 > 解决方案 > React + typescript + Redux 连接功能不起作用

问题描述

我对在 React 中使用 Typescript 有点陌生。我试图将我的 Redux 与我的容器组件连接起来,但由于某种原因,它一直给我类型错误。我经历了许多堆栈溢出帖子,但仍然无法理解发生了什么。

我的 redux tpes 文件:

export interface StoreState {
    languageName: string,
    enthusiasmLevel: number
}

我的容器组件文件:

// React imports
import React from 'react';
import {Link } from 'react-router-dom';
import * as actions from '../../redux/actions/actions';
import { StoreState } from '../../redux/types/types';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';

interface NavbarComponentProps {
  name: string;
  enthusiasmLevel?: number;
  onIcrement?: () => void;
  onDecrement?: () => void;
}

interface DispatchFromProps {
  onDecrement: () => void,
  onIncrement: () => void
}
interface StateFromProps {
  name: string,
  enthusiasmLevel: number
}

type Props = StateFromProps & DispatchFromProps & NavbarComponentProps;

class NavbarContainer extends React.Component<Props, {}> {

  public static defaultProps = {
    enthusiamsLevel: 1
  }

  public render() {
    return (
      <div className='App'>
        navbar works.

        <Link to='/'>left nav</Link>

{/*         
       <p>Hello {name + getExclamationMarks(this.props.enthusiasmLevel)} </p> */}

      <button onClick={this.props.onDecrement}> - </button>
      <button onClick={this.props.onIcrement}> + </button>
      </div>

    );
  }
}

function mapStateToProps({ enthusiasmLevel, languageName}: StoreState) {
  return {
    enthusiasmLevel,
    name: languageName
  }
}

function mapDispatchToProps(dispatch: Dispatch<actions.EnthusiamsAction>) {
  return {
    onDecrement: () => dispatch(actions.decrementEnthusiasm()),
    onIncrement: () => dispatch(actions.incrementEnthusiasm())
  }
}

export default connect<StateFromProps, DispatchFromProps, NavbarComponentProps, StoreState>(mapStateToProps, mapDispatchToProps)(NavbarContainer);

我的错误: 在此处输入图像描述

我猜想将语言名称重置为名称存在问题,但是即使更改也无济于事。

任何帮助将非常感激。干杯!

标签: typescriptreact-redux

解决方案


相关签名如下

<TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>(
    mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
    mapDispatchToProps: MapDispatchToPropsNonObject<TDispatchProps, TOwnProps>
)

省略最后一个State时,默认为{}.

你应该打电话connect<StateFromProps, DispatchFromProps, NavbarContainerProps, StoreState>(...)(...)。想想connect<ReduxInjected, DispatchInjected, GivenByParentWhenUsingThisComponent, ReduxStoreType>

请注意,我稍微更改了界面,您Props应该NavbarContainerProps并且仅包含手动传入的道具(而不是从商店传入)。

然后我喜欢编写一个类型别名type Props = StateFromProps & DispatchFromProps & NavbarContainerProps;,用于定义组件。

class NavbarContainer extends React.Component<Props, {}> {
    ...
}

推荐阅读