如何正确使用路由器使用历史来传递变量? [英] How to properly work with Router using history to pass variables?

查看:47
本文介绍了如何正确使用路由器使用历史来传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个网站,就像 facebook 或我看到的任何其他网站一样,我认为我认为有效(披露:我是网络编程的新手),我想做的是路由到不同的路由,但在我的一个例如,当我进入新页面时,我需要将信息传递到下一个屏幕路由:(我在www.website.com/page1 然后移至 www.website.com/page1/page2),同时通过状态传递数据说我想传递日期或名称,但我不希望它显示在 url 中.所以我发现 react 可以通过:

但是,当我在 (www.website.com/page1/page2) 中通过状态时,只有当我刷新时才无法读取数据,我发现这很奇怪,我会看到通过的数据,我读到历史是可变的,但我无法真正理解这意味着什么,它可能与我的问题有关.到目前为止,我尝试过的代码在这里:

<-------------------- APP--------------------------->

import React, { Component } from 'react';import { BrowserRouter as Router, Route, Switch, IndexRoute, HashRouter } from 'react-router-dom';从 './Page1' 导入 Page1从 './Page2' 导入 Page2从历史"导入 { createBrowserHistory };const history = createBrowserHistory();//idk 如果历史应该在这里class App extends Component {//没有区别构造函数(道具){超级(道具);this.state = {}}使成为() {返回 (<路由器><开关><路由精确路径='/hom/Page1' component={({ match }) =>{ return () }}/><路由精确路径='/hom/Page1/Page2' component={({ match }) =>{ return (<Page2/>) }}/></开关></路由器>)}}导出默认应用程序;

<--------------------Page1----------------->

 import React, { Component } from 'react';从'react-router-dom'导入{链接}类 Page1 扩展组件 {构造函数(道具){超级(道具);this.state = {}}使成为() {返回 (<div><链接到={{路径名:`Page1/Page2`,状态:{ 数据需要:testme"}}}><button>勾选</button></链接>

)}}导出默认Page1;

<-------------------------------第2页---------------------------->

import React, { Component } from 'react';从历史"导入 { createBrowserHistory };const 历史 = createBrowserHistory();类 Page2 扩展组件 {构造函数(道具){超级(道具);this.state = {}}使成为() {控制台日志(history.location.state.dataneed)返回 (<div><h1>{history.location.state.dataneed}</h1>

)}}导出默认第2页;

所以你会看到,一开始你会收到一个错误,但是一旦你刷新,你就会看到正在显示的文本.如果有人可以建议最好的方法去做我正在尝试的事情,如果有人可以帮助我对此事有所了解,我将不胜感激.PS:我使用的是 4.3.1 版本,那里有视频,但那些似乎使用低于 4.0 的版本并且完全不同.

解决方案

我相信这里的问题是 React Router 和 History 包的混合.React Router 使用 History 并在其路由器中内置了历史记录,因此无需显式使用 createBrowserHistory 或直接来自 History 的任何内容.具体问题是 state 从 React Router 传递给 Link,然后您尝试从 createBrowserHistory() 对象.

你可以做些什么来解决这个问题并使你的代码更简洁,基本上不是直接使用 createBrowserHistory 而是依赖于 React Router 的内置历史记录.路由数据可以通过props.locationprops.historyprops.match访问,它们被注入到任何包裹在来自 React Router 的高阶组件 withRouter.

这会是什么样子:

在 index.js 中:

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'react-router-dom'导入{ BrowserRouter};从'./App'导入应用程序;ReactDOM.render((<浏览器路由器><应用程序/></BrowserRouter>), document.getElementById('root'));

在 App.js 中:

import React, { Component } from 'react';import { Route, Switch, withRouter } from 'react-router-dom';从 './Page1' 导入 Page1从 './Page2' 导入 Page2类 App 扩展组件 {构造函数(道具){超级(道具);this.state = {}}使成为() {返回 ({/* 注意不需要路由器,因为我们在 index.js 中的 BrowserRouter 中包装了 App 组件 */}<开关>{/* 注意可以简化组件属性 */}<路由精确路径='/hom/Page1' component={ Page1 }/><路由精确路径='/hom/Page1/Page2' component={ Page2 }/></开关>)}}导出默认 withRouter(App);

Page1 很好.

在第 2 页:

import React, { Component } from 'react';从'react-router-dom'导入{ withRouter };类 Page2 扩展组件 {构造函数(道具){超级(道具);this.state = {}}使成为() {const { dataneed } = this.props.location.state;返回 (<div><h1>{数据需要}</h1>

)}}导出默认 withRouter(Page2);

希望这会有所帮助,如果您有任何问题,请告诉我!

I'm designing a website that just like facebook or anyother website that I seen I assume works (disclosure: I'm new to web programing), what I want to do is to route to different routes but in one of my routes or possibly even more I need to pass info to the next screen route when I to the new page for example: (I'm in www.website.com/page1 then move to www.website.com/page1/page2) whilst passing data through the state say I want to pass a date or a name but I would not want it to be shown in url. So I found that react can pass with:

<Link {to={pathname:"/page2", state:{statetopass:datatopass}}}>

However,when I do pass the state once I'm in (www.website.com/page1/page2) I'm unable to read the data only when I refresh which i find weird will I ever see the data passed, I read that history is mutable but I can't really understand what that means its probably something to do with what my problem is. The code that I have tried so far is here:

<-------------------- APP--------------------------->

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, IndexRoute, HashRouter } from 'react-router-dom';
import Page1 from './Page1'
import Page2 from './Page2'
import { createBrowserHistory } from "history";
const history = createBrowserHistory();//idk if history should be here seems
class App extends Component {//to make no difference
  constructor(props) {
    super(props);
    this.state = {
    }
  }
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path='/hom/Page1' component={({ match }) => { return (<Page1 />) }} />
          <Route exact path='/hom/Page1/Page2' component={({ match }) => { return (<Page2 />) }} />
        </Switch>
      </Router>
    )
  }
}
export default App;

<--------------------Page1----------------->

    import React, { Component } from 'react';
import { Link } from 'react-router-dom'

class Page1 extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }
    render() {
        return (
            <div>
                <Link to={{
                    pathname: `Page1/Page2`,
                    state: { dataneed: "testme" }
                }}><button>Check </button>
                </Link>
            </div>
        )
    }
}
export default Page1;

<-------------------------------Page2----------------------------->

import React, { Component } from 'react';
import { createBrowserHistory } from "history";


const history = createBrowserHistory();

class Page2 extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }
    render() {
        console.log(history.location.state.dataneed)
        return (
            <div>

                    <h1>{history.location.state.dataneed}</h1>

            </div>
        )
    }
}
export default Page2;

So you will see that at first you get an error but then once you refresh you see the text being displayed. If anyone could suggest the best way to go about doing whta I'm trying and if anyone could help me shed some light on the matter I would greatly appreciate this. PS: I'm using 4.3.1 version there are videos out there but those seem to use version lower than 4.0 and completely different.

解决方案

I believe the issue here is the mix of React Router and the History package. React Router uses History and has a history built in to its routers, so there is no need to explicitly use createBrowserHistory or anything from History directly. Specifically the issue is that the state is passed to the Link, from React Router, but then you attempt to access the data from the createBrowserHistory() object.

What you can do to resolve this issue and keep your code a bit cleaner is basically not use createBrowserHistory directly and instead rely on the built-in history from React Router. The routing data can be accessed through props.location, props.history, and props.match, which are injected into any component wrapped in the higher-order component withRouter from React Router.

What this will look like:

In index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>
), document.getElementById('root'));

In App.js:

import React, { Component } from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import Page1 from './Page1'
import Page2 from './Page2'

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
    }
  }

  render() {
    return (
      {/* Note no need for a Router because we wrapped the App component in the BrowserRouter in index.js */}
      <Switch>
        {/* Note the component attribute can be simplified */}
        <Route exact path='/hom/Page1' component={ Page1 } />
        <Route exact path='/hom/Page1/Page2' component={ Page2 } />
      </Switch>
    )
  }
}
export default withRouter(App);

Page1 is fine.

In Page2:

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class Page2 extends Component {
  constructor(props) {
    super(props);
    this.state = {}
  }

  render() {
    const { dataneed } = this.props.location.state;

    return (
      <div>
        <h1>{ dataneed }</h1>
      </div>
    )
  }
}
export default withRouter(Page2);

Hopefully this helps, let me know if you have questions!

这篇关于如何正确使用路由器使用历史来传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆