过在所有跳转的 url
后面添加查询字符串参数进行跳转传参,例如:
// 传入参数 id=2&type=test
Taro.navigateTo({
url: '/pages/page/path/name?id=2&type=test'
})
在目标页的 componentWillMount
生命周期里获取入参:
import { Current } from '@tarojs/taro'
class C extends Taro.Component {
componentWillMount () {
console.log(Current.router.params) // 输出 { id: 2, type: 'test' }
console.log(this.$router.params) // 输出 { id: 2, type: 'test' }
}
}
使用 Taro.navigateBack API :关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages 获取当前的页面栈,决定需要返回几层。那如何向上一页面传递参数呢?
const formPage = Taro.getCurrentPages().slice(-2,-1)[0]
const params = {
...this.props.list
}
formPage.selected = params
Taro.navigateBack({
delta:1
})
我们只需要在上一页面的 componentDidShow 生命周期中获取参数。
async componentDidShow(){
const selected = Taro.getCurrentPages().slice(-1)[0].selected || ''
if(selected){
this.setState(
{
form: {
pickupName: selected.name || '',
......
},
},
() => {
delete Taro.getCurrentPages().slice(-1)[0].selected
}
);
}
}
Taro 小程序与原生开发的小程序有异曲同工之妙,请参考:小程序进入下一页或者返回上一页如何传参