我有几个按钮作为路径。每次改变路线时,我都想确保激活的按钮发生了变化。
有没有办法在react路由器v4中监听路由变化?
我有几个按钮作为路径。每次改变路线时,我都想确保激活的按钮发生了变化。
有没有办法在react路由器v4中监听路由变化?
当前回答
对于React路由器v6和React钩子, 你需要使用useLocation而不是useHistory,因为它已被弃用
import { useLocation } from 'react-router-dom'
import { useEffect } from 'react'
export default function Component() {
const history = useLocation();
useEffect(() => {
console.log('> Router', history.pathname)
}, [history.pathname]);
}
其他回答
您应该使用history v4 lib。
这里的例子
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
对于功能组件,请尝试使用props.location中的useEffect。
import React, {useEffect} from 'react';
const SampleComponent = (props) => {
useEffect(() => {
console.log(props.location);
}, [props.location]);
}
export default SampleComponent;
要在上面的基础上展开,您需要获取history对象。如果您正在使用BrowserRouter,您可以导入withRouter并使用高阶组件(HoC)包装您的组件,以便通过道具访问历史对象的属性和函数。
import { withRouter } from 'react-router-dom';
const myComponent = ({ history }) => {
history.listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
});
return <div>...</div>;
};
export default withRouter(myComponent);
唯一需要注意的是,使用throuter和大多数其他访问历史的方法似乎会污染道具,因为它们将对象解构到其中。
正如其他人所说,这已经被react路由器暴露的钩子所取代,并且它有内存泄漏。如果你在一个函数组件中注册监听器,你应该通过useEffect来做,然后在函数的返回中取消注册。
对于react Hooks,我使用useEffect
import React from 'react'
const history = useHistory()
const queryString = require('query-string')
const parsed = queryString.parse(location.search)
const [search, setSearch] = useState(parsed.search ? parsed.search : '')
useEffect(() => {
const parsedSearch = parsed.search ? parsed.search : ''
if (parsedSearch !== search) {
// do some action! The route Changed!
}
}, [location.search])
在这个例子中,当路由改变时,我向上滚动:
import React from 'react'
import { useLocation } from 'react-router-dom'
const ScrollToTop = () => {
const location = useLocation()
React.useEffect(() => {
window.scrollTo(0, 0)
}, [location.key])
return null
}
export default ScrollToTop
v5.1引入了有用的钩子useLocation
https://reacttraining.com/blog/react-router-v5-1/#uselocation
import { Switch, useLocation } from 'react-router-dom'
function usePageViews() {
let location = useLocation()
useEffect(
() => {
ga.send(['pageview', location.pathname])
},
[location]
)
}
function App() {
usePageViews()
return <Switch>{/* your routes here */}</Switch>
}