react最新版本react-router-dom的路由跳转和传参

相比于之前的版本改变了好多.withrouter,usehistory都没了.

但新版本的路由跳转和传参也挺好上手和使用.

首先我的目录架构是这样,然后跳转的话是从LoginView跳到JiedanView

react最新版本react-router-dom的路由跳转和传参_第1张图片

 

第一种:params传参

第一步路由表配置:

  path:'/jiedan/:id/:title',
        element:

在LoginView中点击触发跳转:

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

function LoginView(props:any) {

  
  const navigate = useNavigate()


  const gotoregister = ()=>{

  

    navigate(`/jiedan/12/南昌`,{replace:false})
    })

    
  }
  return (
    
{ gotoregister() }}>LoginView
) } export default LoginView

JiedanView获取值

import {useParams} from 'react-router-dom'
export default function JiedanView() {
 

  //params传参

  const {id,title} = useParams()

  return (
    
{title}
{id}
) }

第二种:search传参

这种路由表正常配置就好

    path:'/jiedan',
        element:

LoginView的话

import React from 'react'
import {useNavigate } from 'react-router-dom'

function LoginView(props:any) {

  
  const navigate = useNavigate()


  const gotoregister = ()=>{

 
    navigate(`/jiedan?id=13&&title="杭州"`,{replace:false})
   


    
  }
  return (
    
{ gotoregister() }}>LoginView
) } export default LoginView

JiedanView

import {uuseSearchParams} from 'react-router-dom'
export default function JiedanView() {
 
 

  //search传参
  
   const  [search, setSearch] = useSearchParams()
   const id = search.get('id')
   const title = search.get('title')

 

  return (
    
{title}
{id}
) }

第三种:state传参

这个路由和上面一样的不需要额外的配置

LoginView


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

function LoginView(props:any) {

  
  const navigate = useNavigate()


  const gotoregister = ()=>{

  
    navigate(`/jiedan`, { replace: false, state: { id:12, title:"哈哈" } })


  

    
  }
  return (
    
{ gotoregister() }}>LoginView
) } export default LoginView

JiedanView

import {useLocation} from 'react-router-dom'
export default function JiedanView() {

  const {state:{id,title}} = useLocation()




  return (
    
{title}
{id}
) }

至此三大传参就结束啦 

 

 

你可能感兴趣的:(react.js,javascript,前端)