react中使用路由react-router进行页面跳转的方式,以及参数传递方式

方式一,使用withRouter,进行跳转

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import layoutCss from './header.module.scss'

class index extends Component {
  constructor(props) {
    super(props)
  }
  state = {
    menulist: [
      {
        desc: '首页',
        route: '/',
      },
      {
        desc: '新闻',
        route: '/news',
      },
      {
        desc: '个人中心',
        route: '/info',
      },
    ],
  }
  menuHandler = (item, index) => {
    this.props.history.push(item.route)
  }
  render() {
    return (
      
    {this.state.menulist.map((item, index) => { return (
  • {item.desc}
  • ) })}
) } } export default withRouter(index)

参数传递方式:

menuHandler = (item, index) => {
  this.props.history.push(item.route, { age: 13, name: 'zhangsan' })
  // 另外也可以通过location.href search进行传参 this.props.history.push(item.route + '?age=13&name=zhangsan')
}

跳转的页面接收:

import React, { Component } from 'react'

export default class index extends Component {
  constructor(props) {
    super(props)
  }
  componentWillMount(){
    console.log(this.props.location)
  }
  render() {
    return 
个人中心页
} }

输出的结果:页面刷新时数据仍保留

react中使用路由react-router进行页面跳转的方式,以及参数传递方式_第1张图片

方式二,使用react-router-dom提供的Link组件进行页面跳转

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import layoutCss from './header.module.scss'

class index extends Component {
  constructor(props) {
    super(props)
  }
  state = {
    menulist: [
      {
        desc: '首页',
        route: '/',
      },
      {
        desc: '新闻',
        route: '/news',
      },
      {
        desc: '个人中心',
        route: '/info',
      },
    ],
  }
  menuHandler = (item, index) => {
    console.log('点击的菜单为', item.desc)
  }
  render() {
    return (
      
    {this.state.menulist.map((item, index) => { return ( {item.desc} ) })}
) } } export default index

参数传递方式1:

// 方式1

  {item.desc}

跳转的页面接收:页面刷新时数据仍保留

import React, { Component } from 'react'

export default class index extends Component {
  constructor(props) {
    super(props)
  }
  componentWillMount(){
    console.log(this.props.location)
  }
  render() {
    return 
个人中心页
} }

输出的结果:

react中使用路由react-router进行页面跳转的方式,以及参数传递方式_第2张图片

参数传递方式2:

// 方式2

  {item.desc}

跳转页面接收:

import React, { Component } from 'react'

export default class index extends Component {
  constructor(props) {
    super(props)
  }
  componentWillMount(){
    console.log(this.props.location)
  }
  render() {
    return 
个人中心页
} }

输出的结果:

react中使用路由react-router进行页面跳转的方式,以及参数传递方式_第3张图片

注:此种方式传递参数时,页面再次刷新时,参数会丢失。

以上两种是目前查找到的可行的两种方式,后续有其它方式待补充。

 

 

 

你可能感兴趣的:(javascript,react,react,javascript)