如何从反应重击到组件创建可重用类型

时间:2020-06-21 17:51:21

标签: reactjs typescript thunk

这是我的示例代码和框: https://codesandbox.io/s/exampleactioncreator-rh0sm?file=/src/store/examples/actions.tsx

actions.tsx(声明thunk的类型)

import { RootState } from "../../index";
import { Action } from "redux";
import { ThunkAction } from "redux-thunk";
import { actionTypes as at } from "./actionTypes";

type shapePayload = {
  message: string;
};

const acExample = (
  payload: shapePayload
): ThunkAction<void, RootState, unknown, Action<string>> => dispatch => {
  const { message } = payload;
  return dispatch({
    type: at.AC_TYPE_EXAMPLE,
    payload: {
      message,
      somethingelse: true
    }
  });
};

export type shapeExample = ReturnType<typeof acExample>;

export { acExample };

Component.tsx(尝试进行类型转换)

import React, { FC } from "react";
import { connect } from "react-redux";
import { shapeExample, acExample } from "../store/examples/actions";

type shape = {
  acExample: shapeExample;
};
const ExampleActionCreator: FC<shape> = ({ acExample }) => (
  <button
    onClick={() => {
      acExample({ message: "cheese" });
    }}
  >
    trigger store update
  </button>
);

export default connect(
  () => ({}),
  {
    acExample
  }
)(ExampleActionCreator);
错误:
acExample({ message: "cheese" });

错误TypeScript应该有3个参数,但得到1个。10:5

export default connect(
  () => ({}),
  {
    acExample
  }
)(ExampleActionCreator);

错误TypeScript类型'FC'的参数不能分配给'ComponentType void; },形状>>'。类型'FunctionComponent'不能分配给'FunctionComponent void; },形状>>'。属性“ propTypes”的类型不兼容。输入'WeakValidationMap |未定义”不能分配给类型'WeakValidationMap void; },形状>> |未定义”。类型'WeakValidationMap'不能分配给类型'WeakValidationMap void; },形状>>'。属性“ acExample”的类型不兼容。类型'Validator > |未定义”不能分配给类型'Validator <(payload:shapePayload)=> void> |未定义”。类型'Validator >'不能分配给类型'Validator <(payload:shapePayload)=> void>'。不能将类型'ThunkAction '分配给类型'(payload:shapePayload)=> void'。

我一直在尝试使用以下网站的示例:https://redux.js.org/recipes/usage-with-typescript

我找不到一个示例,在该示例中,像在我的示例中一样,它在重装组件时重用了thunk类型。我愿意更改声明类型并返回它的方式,但只需要保留现有的thunk示例。任何想法欢迎。 谢谢

0 个答案:

没有答案