我有几个按钮作为路径。每次改变路线时,我都想确保激活的按钮发生了变化。
有没有办法在react路由器v4中监听路由变化?
我有几个按钮作为路径。每次改变路线时,我都想确保激活的按钮发生了变化。
有没有办法在react路由器v4中监听路由变化?
当前回答
在某些情况下,你可能会使用render attribute而不是component,如下所示:
class App extends React.Component {
constructor (props) {
super(props);
}
onRouteChange (pageId) {
console.log(pageId);
}
render () {
return <Switch>
<Route path="/" exact render={(props) => {
this.onRouteChange('home');
return <HomePage {...props} />;
}} />
<Route path="/checkout" exact render={(props) => {
this.onRouteChange('checkout');
return <CheckoutPage {...props} />;
}} />
</Switch>
}
}
注意,如果你在onRouteChange方法中改变状态,这可能会导致“最大更新深度超出”错误。
其他回答
对于功能组件,请尝试使用props.location中的useEffect。
import React, {useEffect} from 'react';
const SampleComponent = (props) => {
useEffect(() => {
console.log(props.location);
}, [props.location]);
}
export default SampleComponent;
withRouter,历史。listen,和useEffect (React Hooks)一起工作得很好:
import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
const Component = ({ history }) => {
useEffect(() => history.listen(() => {
// do something on route change
// for my example, close a drawer
}), [])
//...
}
export default withRouter(Component)
侦听器回调将在路由更改时触发,并返回历史记录。listen是一个关闭处理程序,可以很好地与useEffect一起使用。
在某些情况下,你可能会使用render attribute而不是component,如下所示:
class App extends React.Component {
constructor (props) {
super(props);
}
onRouteChange (pageId) {
console.log(pageId);
}
render () {
return <Switch>
<Route path="/" exact render={(props) => {
this.onRouteChange('home');
return <HomePage {...props} />;
}} />
<Route path="/checkout" exact render={(props) => {
this.onRouteChange('checkout');
return <CheckoutPage {...props} />;
}} />
</Switch>
}
}
注意,如果你在onRouteChange方法中改变状态,这可能会导致“最大更新深度超出”错误。
我刚刚处理了这个问题,所以我将把我的解答作为其他答案的补充。
这里的问题是useEffect并没有像您希望的那样工作,因为调用只在第一次呈现之后才被触发,因此存在不必要的延迟。 如果您使用一些状态管理器,如redux,您很可能会在屏幕上看到闪烁,因为存储中存在持续的状态。
你真正想要的是使用uselayouteeffect,因为它会立即被触发。
所以我写了一个小的实用函数,我把它放在和路由器相同的目录中:
export const callApis = (fn, path) => {
useLayoutEffect(() => {
fn();
}, [path]);
};
我从组件HOC中调用它,如下所示:
callApis(() => getTopicById({topicId}), path);
path是使用withRouter时在match对象中传递的道具。
我真的不赞成手动地听/不听历史。 这只是我的看法。
import { useHistory } from 'react-router-dom';
const Scroll = () => {
const history = useHistory();
useEffect(() => {
window.scrollTo(0, 0);
}, [history.location.pathname]);
return null;
}