React router 6、使用Navigate如何获取路径名

Bur*_*ton 15 reactjs react-router-dom

我试图了解如何使用 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>
    )
}

Run Code Online (Sandbox Code Playgroud)

lis*_*tdm 25

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

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

 const App = () => {
  const location = useLocation();
  console.log(location.pathname)  
  //...
};
Run Code Online (Sandbox Code Playgroud)