Taro监听路由跳转的实现

3,630 阅读1分钟

记录一个坑,最近遇到的需求,需要在页面跳转的时候判断权限,根据结果执行不同的全局操作。

然而Taro没有提供监听路由跳转的方法。

在网上也没有找到可行性方案。

尝试了很多方法,其中拦截返回事件:window.addEventListener("popstate",()=>{}),可以解决部分问题,但并不是最优解。

最后还是靠自己灵光一闪(ง •̀_•́)ง。

在最外层的入口app.js中,增加一个组件,传入url:window.location.href。

在组件内监听url 变化,执行你想要的操作。

app.js:

import { Component } from 'react'
import { View } from "@tarojs/components";
import MyRouter from "./components/myRouter"
class App extends Component {
  render () {
    return  (
      <View >
        <MyRouter url={window.location.href}></MyRouter>
        {this.props.children}
      </View>
      )
  }
}

export default App

增加一个组件: components/myRouter.js

import { Component } from 'react'
import { View } from "@tarojs/components";

class MyRouter extends Component {
    constructor(props) {
        super(props);
        this.state = {
          url: ''
        };
      }

    componentWillReceiveProps (nextProps) {
        if (nextProps.url !== this.state.url){
          this.setState({
            url: nextProps.url
          })
          // 执行你需要的操作
        }
      }

  render () {
    return  <View></View>
  }
}

export default MyRouter

是不是很简单。

如果要拦截路由跳转,可以在无权限的时候跳转进你需要用户去的页面。