【问题标题】:how to fix programmatic navigation issue using react and typescript如何使用 react 和 typescript 解决程序化导航问题
【发布时间】:2019-06-02 03:37:02
【问题描述】:

我是 react 新手,我正在学习使用 typescript 进行反应编程导航。由于大多数教程都使用 java 脚本,我无法解决使用 typescript 编程导航的问题

就像我尝试过的大多数教程一样

this.props.history.push("/page");

显示错误'history' does not exist on type

我尝试了几种解决方案,例如

 const history=createBrowserHistory();
 history.push("/page") 

此方法将更改 url 路径,但组件不会像这里提到的那样加载 https://github.com/ReactTraining/react-router/issues/4059

我也尝试了另一种解决方案

this.context.push("/page"); 

这给了我以下错误 TypeError: _this.context.push 不是函数

我的完整代码

import * as queryString from 'query-string';
import * as React from 'react';



interface IrentalProps{
name:string,
}



class Rental extends React.Component<IrentalProps, any> {

public extracturl=()=>{

    const stringfy=queryString.parse(location.search);
    return stringfy.id;
}
public handleClick=()=>{
   this.context.push("/page"); //issue 
}
public render() { 
    return ( 
        <div style={{paddingTop:100}}>
        {this.extracturl()}
        <button onClick={this.handleClick}>navigate</button> //calling the function
       </div>
     );
}

}

export default Rental;

我只需要像在 SPA 中使用 typescript 和 browserrouter 一样点击按钮导航到另一个页面

注意:redirect 可以正常工作,并且带有 createhashhistory() 的 hashrouter 也可以正常工作。

【问题讨论】:

    标签: reactjs typescript react-router react-tsx


    【解决方案1】:

    在创建自己的历史记录时,您需要使用 Router 而不是 BrowserRouter 。

    import createBrowserHistory from 'history/createBrowserHistory'
    
    const History = createBrowserHistory()
    export default History;
    

    并将历史传递给路由器的道具

    感谢 BTM

    【讨论】:

      【解决方案2】:

      你需要 react-router 类型。在项目的根目录安装它们(package.json)

      npm install --save @types/react-router

      npm install --save @types/react-router-dom

      【讨论】:

      • 已经在根目录下。我没有在这里导入它们,因为我没有使用这些库的任何依赖项
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2015-12-23
      • 2022-11-15
      • 2020-01-21
      • 1970-01-01
      相关资源
      最近更新 更多