React路由Js跳转方式

13,449 阅读1分钟

前提 npm install react-router-dom

上一篇已经说过react路由和其他框架很不一样,当我想直接使用JS做跳转时发现需要弄的东西真的多。

withRouter 就是主角:

import { withRouter } from 'react-router-dom'

这个方法是把一个非路由管控的组件,变成路由管控的组件,可以使用this.props获取到 history、location、match 使用方法

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

class Demo extends React.Component {
  constructor(props) {
    super(props);
  }

  goBack1() {
    this.props.history.goBack();
  }

  goBack2() {
    this.props.history.go(-1);
  }
  
  goto() {
    this.props.history.push('/url');
  }

  render() {
    return (
      <div style={{margin: '20px'}}>
        <button onClick={() => this.goBack1()} >回退1</button>
        <button onClick={() => this.goBack2()} >回退2</button>
        <button onClick={() => this.goto()} >跳转至URL</button>
      </div>
    )
  }
}

export default withRouter(Demo);

暴露出‘Demo’组件的时候使用withRouter包裹起来,然后‘Demo’组件的this就会加载出history、location、match方法可供使用。

说一下路由传参的三种方式

方式1: 通过params

<Route path='/demo/:id' compontent={test}></Route>

<Link to='/demo/2'>test</Link>

this.props.history.push('/demo/2')

this.props.match.params.id  // 获取id:2

方式2: 通过query

<Link to={ pathname: ' /demo' , query : { name: '两百斤' }}>

this.props.history.push({
    pathname: '/demo',
    query: {
        name: '两百斤'
    }
})

this.props.location.query.name // 获取name:两百斤

方式3: 通过state

<Link to={ pathname: ' /demo' , state : { name: '两百斤' }}>

this.props.history.push({
    pathname: '/demo',
    state: {
        name: '两百斤'
    }
})

this.props.location.state.name // 获取name:两百斤

*query和state基本一样,网上说state比query多了一个加密,但是没有搜索到相关例子,希望大家可以补充一下。