如何解决React中的TS2345编译错误

时间:2019-08-24 20:29:12

标签: javascript reactjs typescript

我尝试在React中编写setState方法。
但是会发生编译错误。
我想知道如何解决这个问题。

前端:react/typesript

articleApi.tsx

import axios from 'axios';
import {Article} from '../articleData';

export const getSingleArticleFactory = (id: string) => {
  const getSingleArticle = async (id: string) => {
    try {
      const response = await axios.get('/api/article/' + id);

      if (response.status !== 200) {
        throw new Error('Server Error');
      }
      const article: Article = response.data;

      return article;
    } catch (err) {
      throw err;
    }
  };
  return getSingleArticle;
};

Detail.tsx

//import

interface ArticleState {
  article: Article;
  redirect: boolean;
  user: firebase.User | null;
}

class Detail extends React.Component<
  RouteComponentProps<{id: string}>,
  ArticleState
> {
  constructor(props: RouteComponentProps<{id: string}>) {
    super(props);
    this.state = {
      article: {
        id: 0,
        title: '',
        content: '',
        imageNames: [],
      },
      redirect: false,
      user: null,
    };
    this.getArticle = this.getArticle.bind(this);
    this.deleteArticle = this.deleteArticle.bind(this);
  }

  getArticle() {
    this.setState({
      //error occures here
      article: api.getSingleArticleFactory(this.props.match.params.id);,
    });
  }

articleData.tsx

export interface Article {
  id: number;
  title: string;
  content: string;
  imageNames: ImageName[];
}

interface ImageName {
  name: string;
}

我希望没有编译错误。
但是实际不是。
我想知道如何解决这个问题。

const getSingleArticleFactory: (id: string) => (id: string) => Promise<Article>
Argument of type '{ article: (id: string) => Promise<Article>; }' is not assignable to parameter of type 'ArticleState | ((prevState: Readonly<ArticleState>, props: Readonly<RouteComponentProps<{ id: string; }, StaticContext, any>>) => ArticleState | Pick<ArticleState, "article"> | null) | Pick<...> | null'.
  Type '{ article: (id: string) => Promise<Article>; }' is not assignable to type 'Pick<ArticleState, "article">'.
    Types of property 'article' are incompatible.
      Type '(id: string) => Promise<Article>' is missing the following properties from type 'Article': id, title, content, imageNamests(2345)

1 个答案:

答案 0 :(得分:-1)

我通过以下方式对其进行了修复:

  async getArticle() {
    const getSingleArticle = api.getSingleArticleFactory();
    const articleData = await getSingleArticle(this.props.match.params.id);
    this.setState({
      article: articleData,
    });
  }
export const getSingleArticleFactory = () => {
  const getSingleArticle = async (id: string) => {
    try {
      const response = await axios.get('/api/article/' + id);

      if (response.status !== 200) {
        throw new Error('Server Error');
      }
      const article: Article = response.data;

      return article;
    } catch (err) {
      throw err;
    }
  };
  return getSingleArticle;
};