如何解决如何将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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。