【问题标题】:how to get previous routing path when navigated to a route in react js?导航到react js中的路由时如何获取以前的路由路径?
【发布时间】:2018-08-20 08:21:14
【问题描述】:

下面是我的 index.js 文件,它包含所有组件的路由路径。当我从另一个组件导航到一个组件时,如何检索以前和当前的路径?

import React from 'react';
import ReactDom from 'react-dom';
import Login from './testApp/login.js';
import Register from './testApp/register.js';
import { BrowserRouter as Router, Route} from "react-router-dom";
import fetch from 'isomorphic-fetch';
class App extends React.Component {
    "eqeqeq":false;
    constructor(props) {
        super(props);
        this.handleSubmit=this.handleSubmit.bind(this);
        this.handleTest=this.handleTest.bind(this);
        this.state={name:{}};
    }
    Greeting() {
        return <h1>ffgdf</h1>
    }
    httpCalling(data) {
       fetch('http://localhost:8080/testingonly', {
        method:'POST',
        mode:'CORS',
        body:JSON.stringify(data),
        headers:{
            'Content-Type':'application/json',
             'Accept': 'application/json'
        }
        }).then(res => res.json()).then(result => {
            localStorage.setItem('myData',JSON.stringify(result));
        });
        const item=localStorage.getItem('myData');
        console.log(JSON.parse(item));
    }
    handleSubmit(data) {
        console.log("++++data++++++++");
        console.log(data);
        console.log("++++data++++++++");
        this.httpCalling(data);
    }


    render() {
        return (

           <Router>
               <div>
                <Route exact path="/" render={(props) => <Login  onSubmit={this.handleSubmit} {...props} />}/>
                {/* add the routes here */}
                <Route path="/test" component={this.Greeting}/>
                <Route path="/register" render={(props) => <Register  />} />
                </div>
          </Router> 
        ) 

    }
}
ReactDom.render(<App />,document.getElementById('root'));

在上面的示例中,您可以看到所有组件都定义在 App 组件的渲染函数中。所以当我从一个组件导航到另一个组件时,如何检测 previos 和当前路由?

【问题讨论】:

  • 需要使用react路由historyapi
  • 你能举个例子吗?
  • 在您的任何顶级容器上的history 道具上进行控制台登录。它应该包含有关路线的所有信息。

标签: reactjs


【解决方案1】:

在您的情况下,基本上路线正在改变。所以你可以使用浏览器窗口的方法来获取当前之前的路线。

获取上一条路线:

window.document.referrer

获取当前路线:

window.location.href

然后您可以使用任何字符串方法来提取您需要的内容。

【讨论】:

猜你喜欢
  • 2020-11-16
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多