我必须根据浏览历史实现一些业务逻辑.
我想做的是这样的:
reactRouter.onUrlChange(url => {
this.history.push(url);
});
当URL更新时,有没有办法从react router接收回调?
我必须根据浏览历史实现一些业务逻辑.
我想做的是这样的:
reactRouter.onUrlChange(url => {
this.history.push(url);
});
当URL更新时,有没有办法从react router接收回调?
在try 检测路由变化时,可以使用history.listen()
功能.考虑到您使用的是react-router v4
,请使用withRouter
HOC包装您的组件,以便访问history
props .
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:
您可以使用监听当前位置的更改
history.listen((location, action) => { console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`) console.log(`The last navigation action was ${action}`) })
location对象实现了窗口的一个子集.地方
**location.pathname** - The path of the URL **location.search** - The URL query string **location.hash** - The URL hash fragment
地点还可能具有以下属性:
location.state-此位置的一些额外状态不在URL中(
createBrowserHistory
和createBrowserHistory
中支持)
location.key
-表示此位置的唯一字符串(支持该操作是
PUSH, REPLACE, or POP
个操作之一,具体取决于用户的操作方式
当您使用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>
)
}
}