【问题标题】:React Redux TS: TypeScript complains about a connect() callReact Redux TS:TypeScript 抱怨 connect() 调用
【发布时间】:2018-10-15 17:15:09
【问题描述】:

我花了几个小时试图弄清楚为什么 TypeScript 不喜欢我的 connect() 调用,但我做不到,因为错误消息有点神秘(就像许多 TypeScript 警告一样)和 Redux 定义文件也很复杂。这是我的 .tsx 文件:

import { addTodo, removeTodo } from "@test-shared/redux";
import { IAppState, ITodoItem } from "@test-shared/types";
import React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import styled from "styled-components/native";
import uuid from "uuid/v4";
import TodoAdder from "./TodoAdder";
import TodoList from "./TodoList";

interface ITodosProps {
  saveTodo: (todo: ITodoItem) => void;
  deleteTodo: (id: string) => void;
  todos: ITodoItem[];
}

/**
 * List and add new Todos
 * @param props
 */
function Todos(props: ITodosProps): JSX.Element {
  const { saveTodo, deleteTodo, todos } = props;

  /**
   * On Todo remove handler
   * @param id
   */
  const onRemove = (id: string) => {
    deleteTodo(id);
  };

  /**
   * On Todo add handler
   * @param text
   */
  const onAdd = (text: string) => {
    const todo = { id: uuid(), text };

    // Save to state
    saveTodo(todo);
  };

  return (
    <TodosView>
      <TodosItems>
        <TodoList todos={todos} onRemove={onRemove} />
      </TodosItems>
      <TodoAdderWrapper>
        <TodoAdder onAdd={onAdd} />
      </TodoAdderWrapper>
    </TodosView>
  );
}

const ConnectedTodos = connect(
  (state: IAppState) => ({
    todos: state.items
  }),
  (dispatch: Dispatch) => ({
    deleteTodo: (id: string) => {
      dispatch(removeTodo(id));
    },
    saveTodo: (todo: ITodoItem) => {
      dispatch(addTodo(todo));
    }
  })
)(Todos);

export default ConnectedTodos;

const TodosView = styled.View`
  flex: 1 0 auto;
  padding: 10px;
`;

const TodoAdderWrapper = styled.View`
  flex-grow: 0;
`;

const TodosItems = styled.View`
  flex-grow: 1;
`;

TypeScript 抱怨 connect() 调用,这是错误:

Argument of type '(props: ITodosProps) => Element' is not assignable to parameter of type 'ComponentType<never>'.
  Type '(props: ITodosProps) => Element' is not assignable to type 'StatelessComponent<never>'.
    Type 'Element' is not assignable to type 'ReactElement<any>'.
      Types of property 'type' are incompatible.

有什么想法吗?

【问题讨论】:

  • 我将代码粘贴到一个文件中,但无法在connect 调用中重现错误,可能是因为我没有从您的项目中导入的其他文件。如果您需要我的帮助,您需要提供足够的代码来重现问题,方法是手动将相关代码组合到一个 sn-p 中,或者发布一个我可以下载的存储库。

标签: typescript redux react-redux


【解决方案1】:

我会试试的

const Todos: React.SFC<ITodosProps> = (props) => {
// your code here
}

但是,如果没有完整的代码,就很难提供帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2021-02-24
    • 2014-02-09
    • 2018-06-06
    • 1970-01-01
    • 2017-07-11
    • 2021-12-19
    相关资源
    最近更新 更多