【问题标题】:Make history.push available in React app.tsx使 history.push 在 React app.tsx 中可用
【发布时间】:2020-05-21 12:12:42
【问题描述】:

将 React 16 与 Typescript 结合使用。在 app.tsx 中的单击处理程序方法中,我需要重定向,以便从应用程序中的任何屏幕进行重定向。但不能在 app.tsx 中使用 this.props.history.push。我们在 app.tsx 中使用了 BrowserRouter。我也需要来自 Modal 组件的类似重定向,但似乎整个应用程序(包括 app.tsx)都没有历史记录。有没有办法做到这一点?我尝试了很多不同的东西,没有任何效果。我需要将 history.push 提供给整个应用程序,每个组件,包括 app.tsx...这可能吗?

这是我的 app.tsx(复制自原始的非通用部分,替换为 ...)

import * as React from 'react'
import { BrowserRouter as Router } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import {RouteComponentProps} from "react-router";
....

export interface DispatchProps {
....
}

export interface AppProps {
loading?: boolean;
...
}

interface State {
...
}


type Props = DispatchProps & AppProps & RouteComponentProps<{}>;

export class App extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);

        this.state = {
            ...
        }
    }

    render() {
        ...
        return (
            <div>
                <Router>
                    <div>
                        <div id="header"></div>
                        .....
                    </div>
                </Router>
                <Footer />
            </div>
        )

    }
}

export default withRouter(App);

这是我的 routes.tsx(复制自原始的非通用部分,替换为 ...)

    import * as React from 'react';
    import { NavLink } from 'react-router-dom';
    import { Route, Redirect, Switch, RouteComponentProps, RouteProps } from 'react-router';

    import withBreadcrumbs, {
      BreadcrumbsRoute,
      InjectedProps,

    } from 'react-router-breadcrumbs-hoc';

    ...

    const routes: BreadcrumbsRoute[] = [
      { path: '/not-found', breadcrumb: '404' },
      { path: '/path1', breadcrumb: 'component1' },
      { path: '/path2', breadcrumb: 'component2' },
        ...  
    ];

    const Breadcrumbs = ({ breadcrumbs }: InjectedProps) => (
    ...
    )

    export const Routes = () => (
      <div>
        <Switch>
            <Route exact={true} path="/not-found" component={NotFound} />
            <Route exact={true} path="/" component={Home} />
            <Route
              exact={true}
              path="/some-path"
              component={SomeComponent}
           />
          <PrivateRoute
            exact={true}
            path="/some-other-path/:some-parameter"
            component={SomeOtherComponent}
          />
          ...
          <Redirect to="/not-found" />
        </Switch>
      </div>
  ); 

    export const x = withBreadcrumbs(routes, { disableDefaults: true })(Breadcrumbs);

    const PrivateRoute = ({ component, ...rest }: RouteProps) => {
        ...
        const render = (props: RouteComponentProps<{}>): React.ReactNode => {
            ...
        }   
    } 

    export default Routes;
    export { x as breadcrumb };

【问题讨论】:

  • @Squiggs.using BrwoserRouter....无法改变这一点。
  • @elvis_ferns 谢谢....如果我添加 withRouter(App),那么 index.tsx 会抛出错误。错误类似于“{} 缺少位置,匹配...”等。尝试在 App 组件中添加 RouteComponentProps,仍然显示错误。尝试使用没有打字稿类型的 npm 包“react-router-global-history”。努力声明模块。
  • @Souvik 请分享您的 App.tsx 和 Routes.tsx 的 sn-p

标签: reactjs typescript react-router


【解决方案1】:

我通过安装一个 npm 包解决了这个问题。 SOF 中有一篇关于同一问题的帖子,作者给出了他/她创建的 npm 包的链接。可惜找不到原帖。它仅适用于 ReactJS,我刚刚使它在 React+TS 中可用。 npm 包是react-router-global-history。以下是我的代码 sn-ps:

这是一个新创建的文件,因为@types 不适用于上述包

src/react-router-global-history.d.ts

/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />

// import { any } from 'expect';
import { History } from 'history'

declare module 'react-router-global-history' {
    export const ReactRouterGlobalHistory: React.ComponentType<any>;
    export default function getHistory(): History;
}

这是我的 app.tsx(复制自原始的非通用部分,替换为省略号)

src/app.tsx

import * as React from 'react'
import { BrowserRouter as Router } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
import {RouteComponentProps} from "react-router";
...
import { ReactRouterGlobalHistory } from 'react-router-global-history';
import getHistory from 'react-router-global-history';
...

export interface DispatchProps {
....
}

export interface AppProps {
loading?: boolean;
...
}

interface State {
...
}


type Props = DispatchProps & AppProps & RouteComponentProps<{}>;

export class App extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);

        this.state = {
            ...
        }
    }

    render() {
        ...
        return (
            <div>
                <Router>
                    <div>
                        <ReactRouterGlobalHistory />
                        <div id="header"></div>
                        .....
                    </div>
                </Router>
                <Footer />
            </div>
        )

    }
    ...
    onClickHandler(someParam: string, event: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
        event.preventDefault();
        ....
        getHistory().push('/some-path');
    }
}

export default App;

PS:我的应用是使用 create-react-app 创建的

【讨论】:

    【解决方案2】:

    您好,我认为您通常不需要应用程序中的路由器组件 withRouter HOC 它具有

    【讨论】:

      【解决方案3】:

      如果您想要 this.props.history.push,那么您必须使用 withRouter HOC 导出您的组件。

      【讨论】:

      • 不工作。在 index.tsx 中显示错误....错误就像“{} 缺少位置,匹配...”
      • 你用过与Router hoc 吗?如果是的话,你能告诉我那个代码吗?
      猜你喜欢
      • 1970-01-01
      • 2021-02-01
      • 2021-03-03
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2019-05-30
      相关资源
      最近更新 更多