【问题标题】:typescript doesn't render dynamic url on reac-router-dom打字稿不会在 react-router-dom 上呈现动态 url
【发布时间】:2020-11-02 00:21:29
【问题描述】:

我有组件 YachtDetails:

import React from "react";
import {RouteComponentProps} from "react-router-dom";

interface Props extends RouteComponentProps<{id:string}> {}

const YachtDetails:React.FC<Props> = ({match}) => {
    return ()

我在 YachtingDetails 中的 App.tsx 上出现错误:

function App() {
    const [show, toggle] = useToggler();


    return (

        <div style={{height: '100%', backgroundColor:'#fff5f5'}}>
            <Toolbar toggle={toggle}/>
            <Drawer show={show} toggle={toggle}/>
            <Backdrop/>
            <main style={{marginTop: '56px'}}>
                <Switch>
                    <Route exact path="/yachts-for-rent/:id">
                        <YachtDetails/> *iget error Type '{}' is missing the following properties from type 'Props': history, location, match
                    </Route>
                </Switch>
            </main>
            <Footer/>
        </div>

    );
}

export default App;

我是初学者,正在尝试创建一个动态 url 并从 json 文件中获取信息。

【问题讨论】:

  • 表示需要传递一些props属性。

标签: reactjs typescript react-router react-router-dom


【解决方案1】:

由于您使用的是打字稿,因此您是在告诉程序组件YachtDetails 必须具有某些属性,否则会引发错误。

这些属性就是这些

interface Props extends RouteComponentProps<{id:string}> {}

所以为了让您的代码能够编译,它应该是:

  const history = useHistory();
  const location = useLocation();
  const match = useRouteMatch();

<YachtDetails history={history} location={location} match={match}/>

如果你只需要match属性,那么你不一定需要扩展RouteComponentProps,你可以这样做:

interface Props {
  match: any
}

【讨论】:

  • const [show, toggle] = useToggler();之后和return之前
  • 我在&lt;YachtDetails history={history} location={location} match={match}/&gt; Type 'match' 上收到错误不能分配给 type 'match'。类型“{}”中缺少属性“id”,但类型“{ id: string; }'。
猜你喜欢
  • 2018-04-23
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 2017-12-15
  • 1970-01-01
相关资源
最近更新 更多