如何将useLocation()与useSelector()结合?

时间:2020-08-11 09:49:36

标签: reactjs react-redux react-router

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),它将成功记录路由更改。这是什么问题?

1 个答案:

答案 0 :(得分:0)

我建议您使用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