反应+打字稿+ Redux连接功能不起作用

时间:2019-01-11 22:06:24

标签: typescript react-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);

我的错误: enter image description here

我猜想将languageName重置为name会有问题,但是即使更改也无济于事。

任何帮助将不胜感激。干杯!

1 个答案:

答案 0 :(得分:1)

相关签名如下

<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, {}> {
    ...
}