访问分派功能作为组件中的道具

时间:2020-01-01 07:22:17

标签: javascript reactjs typescript redux

import React from "react";

import "./cart-dropdown.style.scss";
import { CustomButton } from "../cutom-button/custom-button.component";
import { connect } from "react-redux";
import { StoreState } from "../../redux/root-reducer";
import { ItemModel } from "../../models/ShopPage";
import { CartItem } from "../cart-item/cart-item.component";
import { selectCartItems } from "../../redux/cart/cart.selector";
import { createStructuredSelector } from "reselect";
import { withRouter, RouteComponentProps } from "react-router-dom";

interface CartDropdownStoreProps {
  cartItems: ItemModel[];
}

interface CartDropdownProps extends CartDropdownStoreProps {}

const _CartDropdown: React.FC<CartDropdownProps & RouteComponentProps<{}>> = (
  props: CartDropdownProps & RouteComponentProps<{}>
) => {
  const { cartItems, history } = props;

  return (
    <div className="cart-dropdown">
      <div className="cart-items">
        {cartItems.length ? (
          cartItems.map(cartItem => (
            <CartItem key={cartItem.id} item={cartItem} />
          ))
        ) : (
          <span className="empty-message">Your cart is empty</span>
        )}
      </div>
      <CustomButton onClick={() => history.push("./checkout")}>
        GO TO CHECKOUT
      </CustomButton>
    </div>
  );
};

const mapStateToProps = createStructuredSelector<StoreState, CartDropdownProps>(
  {
    cartItems: selectCartItems
  }
);

export const CartDropdown = withRouter(connect(mapStateToProps)(_CartDropdown));

当我们不将第二个参数传递给connect函数时,我们可以作为组件内部的prop访问dispatch函数,对吗? 已经使用javascript了并且没有抱怨,但是当我尝试使用typescript dispatch函数时,道具中不存在该功能。

我控制台记录该组件获取并分发的所有道具 f 在那里。

我不知道为什么我无法访问它! 有人可以帮我这个吗..?

1 个答案:

答案 0 :(得分:1)

您为_CartDropdown提供的道具类型为CartDropdownProps & RouteComponentProps<{}>。此类型不包含dispatch。因此从TS角度来看,dispatch不存在。

console.log记录由JS表示的对象,并看到dispatch

要解决,请将dispatch类型添加到如下所示的道具类型

import { Dispatch } from 'redux'

const _CartDropdown: React.FC<CartDropdownProps & RouteComponentProps<{}> & {dispatch: Dispatch}> = /* ... */