栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用react-router检测路由更改

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用react-router检测路由更改

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

history.listen()
返回一个
unlisten
函数。您将使用它来
unregister
收听。

您可以像这样配置路线

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);

从历史文档:

您可以使用收听当前位置的更改

history.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}`)
})

location对象实现window.location接口的子集,包括:

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

位置也可能具有以下属性:

location.state- 此位置的某些其他状态,不在URL中(在

createBrowserHistory
和中
受支持
createMemoryHistory

location.key
-代表此位置的唯一字符串(
createBrowserHistory
和中支持
createMemoryHistory

该操作是

PUSH, REPLACe, or POP
取决于用户如何访问当前URL的操作之一。

当您使用react-router v3时,您可以使用如上所述的

history.listen()
from
history
包,也可以使用
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>        )    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448872.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号