【问题标题】:Type '{}' is missing the following properties from type 'RouteComponentProps<{},,>'类型“{}”缺少类型“RouteComponentProps<{},,>”中的以下属性
【发布时间】:2020-10-28 06:08:01
【问题描述】:

所以我对 React 很陌生,尤其是对 Typescript 很陌生。我正在尽我最大的努力把我的头包裹在这一切上!

  1. index.tsx
  2. Router.tsx(所有不同的路由)
  3. LandingFrame.tsx(页面布局)
import React from 'react';

import LandingMain from './LandingMain'

const LandingFrame = () => {
    return (
        <LandingMain/>
    );
}

export default LandingFrame;
  1. LandingMain.tsx(主)
import React, { forwardRef } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';

const YES = gql`
  query yes {
    yes {
      id
      data
      data {
        data
        data
      }
    }
  }
`;

const LandingMain = ({ history }: RouteComponentProps<{}>) => {
  const { loading, error, data } = useQuery(YES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>landing-page.js</h1>
      {data.yes 
        ? <p>Welcome back, {data.yes.data}</p> 
        : <p>Welcome back, Anon</p>
      }
    </div>

  );
};

export default LandingMain;

(第二点)我希望通过拆分登录页面,框架将首先加载,紧随主要组件中的 graphql 查询。这样,当页面加载时,它不仅会在加载其余页面之前在空白页面上返回 &lt;p&gt;Loading...&lt;/p&gt;

TypeScript error in LandingFrame.tsx(22,14):
Type '{}' is missing the following properties from type 'RouteComponentProps<{}, StaticContext, PoorMansUnknown>': history, location, match  TS2739

此时我只是想尽可能多地拆分代码。但是在这样做的同时,我注意到 TS 不会让我像 React 那样轻松地导入组件。根据我的阅读,我需要以某种方式传递道具?

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:
    return (
        <LandingMain/>
    );
    

    LandingMain 期望收到 routeComponentProps,但您在渲染它时没有说 props。您需要添加组件所期望的道具。

    据我了解,登陆框架也在接收 RouteComponentProps,所以这应该可以工作

    const LandingFrame = (props: RouteComponentProps<{}>) => {
        return (
            <LandingMain {...props} />
        );
    }
    

    【讨论】:

    • 您还应该避免在未使用路径属性呈现的组件中使用 RouteComponentProps(基本上在同一个文件中是路由器)。这就是为什么大多数路由器库添加钩子或上下文以允许您访问任何地方的状态,请查看您的库的文档。
    • 在评论中询问关于 react-router v5.1 的钩子的含义的示例是否太过分了?尽管如此,这仍然有效,非常感谢您的帮助:D
    • React 路由器公开了一个名为 useHistory(); 的钩子,您可以使用该钩子从路由器获取当前历史记录,如下所示:const history = useHistory();。它还公开了其他钩子,例如 useLocation() useParams()useRouteMatch() 如果你想要一个简单的教程,你可以找到它 here,你也可以去 here 获取官方 lib 文档。
    • 如果您想或需要了解更多关于钩子的工作原理、可用的钩子或如何创建自己的钩子,您可以前往herehere
    • 正是我需要的!再次非常感谢好先生
    猜你喜欢
    • 2019-09-23
    • 2021-04-20
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2020-05-23
    相关资源
    最近更新 更多