首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Typescript -在路由中传递类型时如何将类型添加到location.state

React Typescript -在路由中传递类型时如何将类型添加到location.state
EN

Stack Overflow用户
提问于 2020-02-22 01:26:27
回答 2查看 9.7K关注 0票数 8

当我传递react-router props发送到Route中的一个组件时,我收到一个错误,因为我有一个特定的状态,我传递了这个组件,但这个错误显示在我的Route中。

以下是路由代码:

代码语言:javascript
复制
<Route
    exact
    path='/flipltimeline'
    render={props => <FliplTimeline {...props} />

在另一个组件中,我在下面调用它

代码语言:javascript
复制
props.history.push(`/flipltimeline`, {
      Approval: singleFliplApprovals,
      InvestigationID,
      Unit: unit,
      Cost: cost
    });

以下是组件的代码。我最终得到了Typescript来编译它,但我必须合并LocationState和TimelineState才能让它工作。但是现在,当我向FliplTimeline组件发送道具时,Typescript会抛出上面的屏幕截图。有谁知道怎么解决这个问题吗?

history.tsx

代码语言:javascript
复制
import { createBrowserHistory } from 'history';

let baseNameProd = '';

if (process.env.NODE_ENV !== 'production') {
  console.log('Looks like we are in development mode!');
  baseNameProd = '';
} else {
  baseNameProd = '/flipl';
}

const customHistory = createBrowserHistory({
  basename: baseNameProd
});

export default customHistory;

FliplTimeline.tsx

代码语言:javascript
复制
import * as React from 'react';
import { History, LocationState } from 'history';

interface FliplTimelineLocationState {
  Approval: any;
  InvestigationID: number;
  Unit: string;
  Cost: number;
}

interface TimelineState{
  state: FliplTimelineLocationState;
}

interface Props {
  history: History;
  location: LocationState & TimelineState;
}

function FliplTimeline(props: Props) {
  return (
    <ModuleTemplate title='Status Timeline' subtitle=''>
      <FliplTimelineJumbotron className='bg-primary-darker shadow-4 line-height-serif-4'>
        <div className='grid-row'>
          <div className='grid-col-4'>
            <span
              className='font-mono-2xl text-white'
              style={{
                verticalAlign: 'middle'
              }}
            >
              FLIPL{' '}
            </span>
            <span
              className='font-mono-xl text-gold'
              style={{
                verticalAlign: 'middle'
              }}
            >
              {props.location.state.InvestigationID}
            </span>

更新:添加了我的history.tsx文件,我在其中为React-Router创建了自己的历史记录。在导入语句中也添加了。

更新:尝试将我的FliplTimeline组件更改为具有此接口

代码语言:javascript
复制
import { RouteComponentProps } from 'react-router-dom'

function FliplTimeline(props: RouteComponentProps ) {

我得到两个错误。第一个是这个,另一个是说道具的形状是错误的。想法?

更新:我终于能够为我的组件获得正确的props声明。

代码语言:javascript
复制
import { RouteComponentProps } from 'react-router-dom';

interface FliplTimelineLocationState {
  Approval: any;
  InvestigationID: number;
  Unit: string;
  Cost: number;
}

function FliplTimeline(
  props: RouteComponentProps<{}, any, FliplTimelineLocationState | any>
)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-25 01:01:37

我能让它工作起来。

代码语言:javascript
复制
import { RouteComponentProps } from 'react-router-dom';

interface FliplTimelineLocationState {
  Approval: any;
  InvestigationID: number;
  Unit: string;
  Cost: number;
}

function FliplTimeline(
  props: RouteComponentProps<{}, any, FliplTimelineLocationState | any>
)
票数 7
EN

Stack Overflow用户

发布于 2020-02-22 01:56:06

使用RouteComponentProps并为其泛型提供适当的类型。本文涵盖了相当多的内容:How to Use React Router in Typescript

将React Router与TypeScript一起使用几乎需要填充React Router所具有的泛型。否则,没有足够的上下文来确定所有内容的类型。与我下面的示例进行比较。我使用useHistory并用我想要提供的类型填充它。这可能是您的FliplTimelineLocationState,这样historystate属性就可以确定为FliplTimelineLocationState类型。

代码语言:javascript
复制
import React, {MouseEventHandler} from "react";
import {Route, RouteComponentProps, StaticContext, useHistory} from "react-router";
import {BrowserRouter, Link} from "react-router-dom";

interface IMyScreenRouteParams {
    foo: string;
}

// You don't have to extend, you could just use StaticContext
interface IMyStaticContext extends StaticContext {
    bar: string;
}

interface IHistory {
    fizz: string;
}

const Nav = () => {
    const history = useHistory<IHistory>();

    const clickHanlder: MouseEventHandler = () => {
        history.push("/my-screen", {
            fizz: "you said fizz"
        });
    };

    return (
        <nav>
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/my-screen">My Screen</Link></li>
                <li><button onClick={clickHanlder}>My Screen with state</button></li>
                <li><Link to="/my-screen?q=hello">My Screen with query</Link></li>
                <li><Link to="/my-screen/bob">My Screen using match</Link></li>
            </ul>
            <div>
                <button onClick={() => history.goBack()}>Back</button>
                <button onClick={() => history.push("/")}>Home</button>
                <button onClick={() => history.goForward()}>Forward</button>
            </div>
        </nav>
    );
};

const MyScreen = ({
    location,
    match,
    history,
    staticContext
}: RouteComponentProps<IMyScreenRouteParams, IMyStaticContext, IHistory>) => (
    <div>
        <section>
            <h2>Location</h2>
            <p><code>location</code> has <code>IHistory</code> props.</p>
            <pre><code>{JSON.stringify(location, null, 4)}</code></pre>
        </section>
        <section>
            <h2>Match</h2>
            <p><code>match</code> has <code>IMyScreenRouteParams</code> props.</p>
            <pre><code>{JSON.stringify(match, null, 4)}</code></pre>
        </section>
        <section>
            <h2>History</h2>
            <p><code>history</code> has <code>IHistory</code> props.</p>
            <pre><code>{JSON.stringify(history, null, 4)}</code></pre>
        </section>
        <section>
            <h2>Static Context</h2>
            <p><code>staticContext</code> has <code>IMyStaticContext</code> props or whatever static context your router has.</p>
            <p>This is for a <a href="https://reacttraining.com/react-router/web/api/StaticRouter/context-object"><code>&lt;StaticRouter/&gt;</code></a>.</p>
            <pre><code>{JSON.stringify(staticContext, null, 4)}</code></pre>
        </section>
    </div>
);

const Router = () => (
    <BrowserRouter>
        <div
            style={{
                display: "flex",
                flexDirection: "row"
            }}
        >
            <Nav />
            <main>
                <Route exact path="/" component={() => (<div>Click something in the <code>&lt;nav/&gt;</code></div>)} />
                <Route exact path="/my-screen" component={MyScreen} />
                <Route exact path="/my-screen/:id" component={MyScreen} />
            </main>
        </div>
    </BrowserRouter>
);

export default Router;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60343598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档