javascript - 在组件中作为 prop 访问调度函数

标签 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 函数时,我们可以在组件内部将 dispatch 函数作为 prop 访问,对吧? 已经使用 javascript 并且没有提示,但是当我尝试使用 typescript dispatch 函数时, Prop 中不存在。

我控制台记录了该组件获取和分发的所有 Prop f 存在于那里。

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

最佳答案

您为 _CartDropdown 提供了 Prop 类型作为CartDropdownProps & RouteComponentProps<{}> .此类型不包含 dispatch .所以从TS的 Angular 来看dispatch不存在。

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

要解决,请添加 dispatch 的类型像下面这样的 Prop 类型

import { Dispatch } from 'redux'

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

关于javascript - 在组件中作为 prop 访问调度函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550698/

相关文章:

javascript - 使用 javascript 或 ajax 在同一页面中打开链接

reactjs - 如何使用 Jest 和 react-testing-library 测试 Websocket 客户端

javascript - onKeyDown 会在各处触发,而不仅仅是在一页上触发

typescript - 在 Ionic 中应用幻灯片

javascript - 英特尔 XDK 模拟器中的 ECMAScript 生成器

javascript - 无法创建长度超过 0x3ffffffe7 个字符的字符串

javascript - 在 jQuery 中使用 filter() 更有效,还是只在 each() 中使用?

javascript - 如何在 React Hooks 中触发从子级到父级的状态更改?

javascript - 组件选择器标签上的 Angular 2 样式?

angular - Angular 4 中的多个日期选择器并且没有 jquery