gpt4 book ai didi

reactjs - 使用react-router检测路由变化

转载 作者:行者123 更新时间:2023-12-03 12:55:02 26 4
gpt4 key购买 nike

我必须根据浏览历史记录实现一些业务逻辑。

我想做的是这样的:

reactRouter.onUrlChange(url => {
this.history.push(url);
});

当 URL 更新时,有什么方法可以接收来自 React-router 的回调吗?

最佳答案

您可以使用history.listen()尝试检测路线变化时的功能。考虑到您正在使用 react-router v4,请使用 withRouter HOC 包装您的组件以访问 history 属性。

history.listen() 返回一个unlisten 函数。您可以使用它来取消注册监听。

您可以像这样配置您的路线

index.js

ReactDOM.render(
<BrowserRouter>
<AppContainer>
<Route exact path="/" Component={...} />
<Route exact path="/Home" Component={...} />
</AppContainer>
</BrowserRouter>,
document.getElementById('root')
);

然后在AppContainer.js

class App extends Component {

componentWillMount() {
this.unlisten = this.props.history.listen((location, action) => {
console.log("on route change");
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<div>{this.props.children}</div>
);
}
}
export default withRouter(App);

来自历史docs :

You can listen for changes to the current location usinghistory.listen:

history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})

The location object implements a subset of the window.locationinterface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

Locations may also have the following properties:

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory andcreateMemoryHistory)

location.key - A unique string representing this location (supportedin createBrowserHistory and createMemoryHistory)

The action is one of PUSH, REPLACE, or POP depending on how the usergot to the current URL.

当你使用react-router v3时,你可以使用上面提到的history包中的history.listen(),或者你也可以使用 browserHistory.listen()

您可以配置和使用您的路线,例如

import {browserHistory} from 'react-router';

class App extends React.Component {

componentDidMount() {
this.unlisten = browserHistory.listen( location => {
console.log('route changes');

});

}
componentWillUnmount() {
this.unlisten();

}
render() {
return (
<Route path="/" onChange={yourHandler} component={AppContainer}>
<IndexRoute component={StaticContainer} />
<Route path="/a" component={ContainerA} />
<Route path="/b" component={ContainerB} />
</Route>
)
}
}

关于reactjs - 使用react-router检测路由变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com