【问题标题】:React router 6, useNavigate how to get pathnameReact router 6,使用导航如何获取路径名
【发布时间】:2020-12-05 17:07:19
【问题描述】:

我正在尝试了解如何使用 react router 6 和 useNavigate,但不知道如何获取当前路径名。

使用 useHistory 我可以使用history.location.pathname 来获取当前网址。但是如何使用 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>
    )
}

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

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

    import {  useLocation } from 'react-router-dom';
    
     const App = () => {
      const location = useLocation();
      console.log(location.pathname)  
      //...
    };
    

    【讨论】:

      【解决方案2】:

      这可以通过全局属性window.location.pathname 访问,无需使用useHistoryuseNavigate 挂钩

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 1970-01-01
        • 2020-07-01
        • 2014-08-09
        • 1970-01-01
        • 2018-11-03
        • 2020-09-11
        • 2022-11-27
        • 1970-01-01
        相关资源
        最近更新 更多