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

我想做的是这样的:

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

当URL更新时,有没有办法从react router接收回调?

推荐答案

在try 检测路由变化时,可以使用history.listen()功能.考虑到您使用的是react-router v4,请使用withRouter HOC包装您的组件,以便访问historyprops .

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中(createBrowserHistorycreateBrowserHistory中支持)

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

Reactjs相关问答推荐

实时收听react前端应用程序中的webhook响应

无法在列表中看到文本

为什么我的react虚拟化列表不显示滚动条,除非我确保高度低于rowCount*rowHeight?

使用下一步中的路由/导航不会立即加载路由

Redux工具包-useSelector如何通过Reducer引用InitialState?

如何通过reactjs正确显示记录

悬停轴时重新绘制自定义参照线

通过createRoot创建的React元素无法调用Provider值

如何在 TimePicker 中更改时钟 colored颜色 和确定按钮字体 colored颜色 - MUI React

为 Next.js 应用程序目录中的所有页面添加逻辑的全局文件是什么?

如何将 MUI X 数据网格单元格方向更改为行级而不是列级?

无法从子组件传递数据到父组件

未捕获的运行时错误:对象作为 React 子项无效

我应该如何将字符串作为props 传递给 React 组件?

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

在 Formik 表单中访问子组件的值

如何使用 UseState 正确测试组件

理解 React 中的 PrevState

如何在 React JS 上使文本中的单词可点击

当父组件重新渲染时做出react ,我失go 了子状态.我错过了什么?