我花了数小时试图弄清楚为什么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.
有什么想法吗?
答案 0 :(得分:0)
我会尝试
const Todos: React.SFC<ITodosProps> = (props) => {
// your code here
}
尽管没有完整的代码也很难提供帮助。