首页 > 解决方案 > React router 6,使用Navigate如何获取路径名

问题描述

我试图了解如何使用 react router 6 和 useNavigate 但无法弄清楚如何获取当前路径名。

使用 useHistory 我可以history.location.pathname用来获取当前的 url。但是我如何使用 useNavigate 来做同样的事情呢?

import React, {useState} from 'react'
import styed from 'styled-components'
import { useNavigate } from 'react-router-dom'
import { MovieState } from '../movieState'

export const MovieDetail = () => {
    let navigate = useNavigate();
    const [movies, setMovies] = useState(MovieState)
    const [movie, setMovie] = useState(null)
    //const url = navigate.location.pathname;
    return (
        <div>
            <h1>MovieDetail</h1>
        </div>
    )
}

标签: reactjsreact-router-dom

解决方案


如果您需要访问 location.pathname,请使用useLocation挂钩:

import {  useLocation } from 'react-router-dom';

 const App = () => {
  const location = useLocation();
  console.log(location.pathname)  
  //...
};

推荐阅读