如何将useLocation与useSelector结合?

问题描述

import React from "react"
import { useSelector } from 'react-redux'
import { useLocation } from "react-router"

const BreadCrumb = () => {

  const location = useLocation()

  const currentPageTitle = useSelector(state => {

    // match current location to get the currrent page title from redux store and return it
  })

  return (

    <h2>Home / { currentPageTitle}</h2>

  )
}

export default BreadCrumb

此代码在初始渲染中工作正常,并且确实获得了预期的结果{ currentPageTitle },但UI似乎没有重新渲染,即使更改了路线也保持不变。虽然,如果我在return语句之前使用console.log(location),它将成功记录路由更改。这是什么问题?

解决方法

我建议您使用useEffect钩子:

import React,{ useEffect,useState } from "react"
import { useSelector } from 'react-redux'
import { useLocation } from "react-router"

const BreadCrumb = () => {
  const location = useLocation()
  const [currentLocation,setCurrentLocation] = useState('')

  const currentPageTitle = useSelector(state => {
    console.log(currentLocation);
    // Do something with currentLocation
  })

  useEffect(() => {
    if (location) {
      setCurrentLocation(location.pathname)
    } else {
      setCurrentLocation('')
    }
  },[location])

  return (

    <h2>Home / { currentPageTitle}</h2>

  )
}

export default BreadCrumb

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...