[Taro入门:4] 路由

2,620 阅读5分钟

这是我参与更文挑战的第2天,活动详情查看:更文挑战

一、介绍

Taro中自带了路由功能,其API与微信小程序保持一致,包括以下API:

API参数描述
Taro.switchTab{url:必填,跳转路径字符串,complete:接口调用结束时回调,success:成功时回调,fail:失败时回调}跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
Taro.reLaunch{url:必填,跳转路径字符串,complete:接口调用结束时回调,success:成功时回调,fail:失败时回调}关闭所有页面,打开应用内的某个页面
Taro.redirectTo{url:必填,跳转路径字符串,不能是tabBar的页面路径,complete:接口调用结束时回调,success:成功时回调,fail:失败时回调}关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
Taro.navigateTo{url:必填,跳转路径字符串,不能是tabBar的页面路径,complete:接口调用结束时回调,success:成功时回调,fail:失败时回调}保留当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
Taro.navigateBack{delta:返回的页面数,若超过现有页面数,则返回首页,complete:接口调用结束时回调,success:成功时回调,fail:失败时回调}关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages 获取当前的页面栈,决定需要返回几层。

注意:小程序中页面栈最多十层,达到十层之后再使用Taro.navigateTo会报错navigateTo:fail webview count limit exceed

image.png

二、Api实践

2.1:Taro.switchTab

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。 tabbar使用时,需要在app.config.js中进行配置:

// app.config.js 
export default {
// 省略其他配置
pages: [
    'pages/index/index',
    'pages/index/introduce/introduce',
    'pages/index/latest-version/latest-version',
    'pages/mengde/index',
    'pages/liyue/index'
  ],
  tabBar: {
    "color": "#000000",
    "selectedColor": "#3cc51f",
    "backgroundColor": "#E1FFFF",
    "list": [{
      "pagePath": "pages/index/index",
      "iconPath": "image/icon_component.png",
      "selectedIconPath": "image/icon_component.png",
      "text": "首页"
    }, {
      "pagePath": "pages/mengde/index",
      "iconPath": "image/奇异果.png",
      "selectedIconPath": "image/奇异果.png",
      "text": "蒙德"
    }, {
      "pagePath": "pages/liyue/index",
      "iconPath": "image/圣女果.png",
      "selectedIconPath": "image/圣女果.png",
      "text": "璃月"
    }]
  },
}
// 使用示例
import { Component } from 'react'
import { View,Button } from '@tarojs/components'
import Taro from '@tarojs/taro'

export default class Index extends Component {
  render () {
    return (
      <View className='introduce'>
        《原神》是一款开放世界冒险游戏,这意味着从你踏入「提瓦特」的第一刻起,只要合理规划自己的体力,不论翻山越岭、还是横渡江河,总有办法见到新的风景。
        <View class="index-tabs">
          <Button onClick={()=>{Taro.switchTab({url:'/pages/mengde/index'})}}>蒙德</Button>
          <Button onClick={()=>{Taro.switchTab({url:'/pages/liyue/index'})}}>璃月</Button>
        </View>
      </View>
    )
  }
}

使用switchTab与直接点击tabbar选项的体验是一致的,个人觉得主要用于:非tabbar页面跳转tabbar页面,因为非tabbar页面上不展示tabbar,无法通过点击tabbar的方式进行跳转。

2.2:Taro.reLaunch

关闭所有页面,打开应用内的某个页面。

// src\pages\index\latest-version\latest-version.jsx
import { Component } from 'react'
import { View,Button } from '@tarojs/components'
import Taro,{getCurrentPages} from '@tarojs/taro'

export default class Index extends Component {
    componentDidMount(){
        // 打印当前的页面栈
        console.log('getCurrentPages()',getCurrentPages())
    }
  render () {
    return (
      <View className='introduce'>
        《原神》「玉扉绕尘歌」1.5版本
        <Button onClick={()=>Taro.reLaunch({url:'/pages/index/latest-version/latest-version'})}>ReLaunch</Button>
        <View>
        </View>
      </View>
    )
  }
}

我们在页面mount时,调用getCurrentPages打印当前的页面栈。观察从首页进入此页面和reLaunch此页面 时的页面栈: image.png 可以看到:

  • 从首页进入该页面时,页面栈中有首页和该页面两条记录,顶部导航栏的左侧显示的是Back按钮。
  • reLaunch进入页面时,页面栈中仅有该页面的记录,顶部导航栏的左侧显示的是Home按钮。 reLaunch时会先关闭所有页面,再打开指定页面,因此小程序会有刷新的动作。

2.3:Taro.redirectTo / Taro.navigateTo

关闭/保留当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。

这2个Api功能基本上一致,区别在于是否保留当前页面在页面栈中,即是否可以通过Back返回到当前页面。

// src\pages\index\index.jsx
import { Component } from 'react'
import { View, Text, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './index.scss'

export default class Index extends Component {

  render() {
    return (
      <View className='index'>
        <Text>Hello 原神!</Text>
        <View class="index-tabs">
          <Button onClick={() => Taro.navigateTo({
            url: '/pages/index/introduce/introduce'
          })}>介绍</Button>
          <Button onClick={() => Taro.redirectTo({
            url: '/pages/index/latest-version/latest-version'
          })}>最新版本</Button>
        </View>
      </View>
    )
  }
}

2.4:Taro.navigateBack

关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages 获取当前的页面栈,决定需要返回几层。 当不传参数时,默认返回上一页面;也可以通过传入{delta:number}指定返回的层数。

// src\pages\index\introduce\introduce.jsx
import { Component } from 'react'
import { View,Button } from '@tarojs/components'
import Taro from '@tarojs/taro'

export default class Index extends Component {
  render () {
    return (
      <View className='introduce'>
        《原神》是一款开放世界冒险游戏,这意味着从你踏入「提瓦特」的第一刻起,只要合理规划自己的体力,不论翻山越岭、还是横渡江河,总有办法见到新的风景。
        <Button onClick={()=>Taro.navigateBack()}>返回</Button>
      </View>
    )
  }
}

三、页面栈

页面栈是指微信小程序中页面访问的记录,小程序中页面栈最多维护10条,当栈中有10条记录时,就无法通过Taro.navigateTo进行页面跳转了。

Api对页面栈的影响
Taro.switchTab清空页面栈, 并压入跳转的tabbar页面
Taro.reLaunch清空页面栈, 并压入跳转后页面
Taro.redirectTo跳转后的页面替换当前栈顶的记录,栈的长度保持不变
Taro.navigateTo跳转后的页面压入到栈宏,栈的长度+1;当栈中有10条记录时会报错,无法跳转
Taro.navigateBack根据参数delta值返回的层级将栈中的元素弹出,栈的长度-delta

四、路由传参

4.1 传参介绍与实践

页面跳转时,可以通过在url后面添加参数的方式将参数传递至新页面。 参数与路径之间使用 ? 分隔,参数键与参数值用 = 相连,不同参数用 & 分隔;如 'path?key=value&key2=value2'。

// index.jsx
import { Component } from 'react'
import { View, Text, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './index.scss'

export default class Index extends Component {
  render() {
    return (
      <View className='index'>
        <Text>Hello 原神!</Text>
        <View class="index-tabs">
          <Button onClick={() => Taro.navigateTo({
            url: '/pages/index/introduce/introduce?date=2021-06-02&weather=sunny'
          })}>介绍</Button>
        </View>
      </View>
    )
  }
}

// 跳转页 introduce.jsx
import { Component } from 'react'
import { View,Button } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state={}
  }
  componentDidMount(){
    let {date,weather } = getCurrentInstance().router.params
    console.log('date,weather',date,weather)
    this.setState({
      date,
      weather
    })
  }
  render () {
    return (
      <View className='introduce'>
        《原神》是一款开放世界冒险游戏,这意味着从你踏入「提瓦特」的第一刻起,只要合理规划自己的体力,不论翻山越岭、还是横渡江河,总有办法见到新的风景。
          <View>Date:{this.state.date}</View>
          <View>Weather:{this.state.weather}</View>
      </View>
    )
  }
}

页面效果:

image.png

4.2 各Api能否路由传参

Api能否传参
Taro.switchTab路径后不可携带参数
Taro.reLaunch路径后可以带参数
Taro.redirectTo路径后可以带参数
Taro.navigateTo路径后可以带参数
Taro.navigateBack/