Ahm*_*sen 4 reactjs react-native react-native-navigation
我在当前状态为 {key:'value'} 的屏幕 A 上,我导航到屏幕 B
现在我试图再次从屏幕 B 弹出到屏幕 A,但我不想丢失屏幕 A {key:'value'} 中的当前状态
一些解决方案是将数据保存在 AsynStorage 中,并在返回屏幕 A 时检索它,但这不是一个好习惯
.pop() 这样做,但如果我需要返回额外的参数怎么办?
Navigation.pop(this.props.componentId , {
passProps: {
data : 'current',
more : 'just-example'
}});
Run Code Online (Sandbox Code Playgroud)
上面的代码,不起作用
有什么建议 ?
我不使用任何状态管理工具,如 Redux/Mobx ..
我发现一个很好的解决方案是发送带有参数的回调函数
在屏幕 A
getback(success)
{
alert(success);
}
Navigation.push(this.props.componentId , { component : {
name : "Payment",
passProps: {
subscription : current,
getback: this.getback
},
}});
Run Code Online (Sandbox Code Playgroud)
然后在屏幕 B 中,当您弹出屏幕 A 时,会触发 getback 功能
Navigation.pop(this.props.componentId);
this.props.getback(true);
Run Code Online (Sandbox Code Playgroud)
这对我很有效
我一直致力于此,并取得了成就react-navigation。
基本上,组件 A 会将组件 A 的导航状态发送给组件 B。因此,对于 B 的角度来看,它将是堆叠 B 组件之前的 prevState。
因此,当组件 B 使用之前的导航状态导航“返回”到组件 A 时,就好像您的导航状态从未改变,现在您可以使用第二个参数 将navigate参数发送回组件 A。
这个简单的例子说明了这种做法,我认为它是完全有效的,没有任何AsyncStorage用途。
// In Component A use a custom prevState when goes to Component B
const { navigation } = this.props;
navigation.navigate('ComponentB', { prevState: navigation.state });
Run Code Online (Sandbox Code Playgroud)
// In Component B use this custom goBack to "pop" to last screen
function goBack(data) {
const { navigation } = this.props;
const { routeName, key } = navigation.getParam('prevState');
navigation.navigate({ routeName, key, params: data });
}
Run Code Online (Sandbox Code Playgroud)
// And finally in Component A again you could get data like this
function getDataFromComponentB() {
const { navigation } = this.props;
// It is null if no parameters are specified!
return navigation.state.params;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10772 次 |
| 最近记录: |