简体   繁体   English

带有 React 路由器的 TypeScript

[英]TypeScript with React Routers

I am new to typescript and react.我是打字稿和反应的新手。 I am using react-router-dom to create routes in my react app.我正在使用 react-router-dom 在我的 React 应用程序中创建路由。 I can directly use /posts as hardcoded value, but I want to try relative paths to fetch the posts.我可以直接使用 /posts 作为硬编码值,但我想尝试使用相对路径来获取帖子。 I have added the code below.我已经添加了下面的代码。 Can you please tell me how can I fix type PostsPropsType?你能告诉我如何修复 PostsPropsType 类型吗?

Posts.tsx - 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 - 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>
  );
}

And the error I am having is -我遇到的错误是-

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 | 

The render prop on Route gets passed the history, location, and match objects. Route上的render道具传递了历史记录、位置和匹配对象。 You're currently not forwarding them along to Posts , as required by PostsPropsType .您目前没有按照PostsPropsType要求将它们转发到Posts So instead of this:所以而不是这个:

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

// ...

render={() => postsElement}

Do this:做这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM