【问题标题】:TypeScript with React Routers带有 React 路由器的 TypeScript
【发布时间】:2020-08-23 16:50:42
【问题描述】:

我是打字稿的新手并做出反应。 我正在使用 react-router-dom 在我的反应应用程序中创建路由。我可以直接使用 /posts 作为硬编码值,但我想尝试相对路径来获取帖子。我在下面添加了代码。 你能告诉我如何修复 PostsPropsType 类型吗?

Posts.tsx -

import styles from "./Posts.module.css";
import { Link, RouteComponentProps } from "react-router-dom";
 
export type postType = {
  title: string;
  author: string;
  id: string;
};
 
type PostsPropsType = {
  postsData: postType[];
  postClick: Function;
} & RouteComponentProps;
 
export default function Posts(props: PostsPropsType) {
  const posts = props.postsData.map((post: postType, index: number) => {
    return (
      <Link to={`/${props.match.url}/${post.id}`}>
        <div
          className={styles.Post}
          key={index}
          onClick={() => props.postClick(post.id)}
        >
          <h3>
            <strong>{post.title}</strong>
          </h3>
          <div className={styles.Author}>{post.author}</div>
        </div>
      </Link>
    );
  });
  return <div className={styles.Posts}>{posts}</div>;
}

App.tsx -

import React, { useState, useEffect } from "react";
import styles from "./App.module.css";

import Posts from "../components/Posts/Posts";
import { postType } from "../components/Posts/Posts";
import FullPost from "../components/FullPost/FullPost";
import { fullPostType } from "../components/FullPost/FullPost";
import NewPost from "../components/NewPost/NewPost";
import { BrowserRouter, Link, Route, Switch, Router } from "react-router-dom";

import jpaxios from "../apis/jsonplaceholder.axios";

export default function App(props: {}) {
  let [postsState, setPostsState] = useState<postType[]>();
  let [fullPostState, setFullPostState] = useState<fullPostType>({
    id: "0",
    body: "body",
    title: "Title",
  });

  useEffect(() => {
    jpaxios.get<postType[]>("/posts").then((response) => {
      const postsData = response.data.slice(0, 3);
      const posts = postsData.map((post: postType) => {
        return { title: post.title, author: "katsura", id: post.id };
      });
      setPostsState(posts);
    });
  }, []);

  const fullPostButtonHandler = (id: string) => {
    fullPostState?.id !== id &&
      jpaxios.get<fullPostType>(`/posts/${id}`).then((response) => {
        setFullPostState({
          id: id,
          body: response.data.body,
          title: response.data.title,
        });
      });
  };

  const fullPostDeleteHandler = (id: string) => {
    id !== "0" &&
      setFullPostState({
        id: "0",
        body: "body",
        title: "title",
      });
  };

  let postsElement = <div>Loading...</div>;
  if (postsState) {
    postsElement = (
      <Posts postsData={postsState} postClick={fullPostButtonHandler} />
    );
  }

  return (
    <BrowserRouter>
      <div className={styles.APP}>
        <ul>
          <li>
            <Link to="/new-post">New Post</Link>
          </li>
          <li>
            <Link to="/posts">Posts</Link>
          </li>
          <li>
            <Link to="/full-post">Full Post</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/posts" exact render={() => postsElement} />
          <Route path="/new-post" exact component={NewPost} />
        </Switch>
        <Route
          path={["/full-post", "/posts/:id"]}
          exact
          render={() => (
            <FullPost
              fullPost={fullPostState}
              deleteHandler={fullPostDeleteHandler}
            />
          )}
        />
      </div>
    </BrowserRouter>
  );
}

我遇到的错误是 -

TypeScript error in /Users/parth/Documents/personal-git/react-playbook/axios-with-hooks/src/containers/App.tsx(54,8):
Type '{ postsData: postType[]; postClick: (id: string) => void; }' is missing the following properties from type 'RouteComponentProps<{}, StaticContext, UnknownFacade>': history, location, match  TS2739

    52 |   if (postsState) {
    53 |     postsElement = (
  > 54 |       <Posts postsData={postsState} postClick={fullPostButtonHandler} />
       |        ^
    55 |     );
    56 |   }
    57 | 

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    Route 上的 render 属性传递了历史、位置和匹配对象。您目前没有按照PostsPropsType 的要求将它们转发到Posts。所以不要这样:

    let postsElement = <div>Loading...</div>;
    if (postsState) {
      postsElement = (
        <Posts postsData={postsState} postClick={fullPostButtonHandler} />
      );
    }
    
    // ...
    
    render={() => postsElement}
    

    这样做:

    render={(routeProps) => (
      postsState ? (
        <Posts {...routeProps} postsData={postsState} postClick={fullPostButtonHandler} />
      ) : (
        <div>Loading...</div>
      )
    )}
    

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2020-10-07
      • 2017-12-14
      • 2019-09-12
      • 2016-03-24
      • 2023-02-07
      相关资源
      最近更新 更多