[英]How to send data back to previous sceen when using navigation.goBack()?
I've got screen 1 from which I navigate to screen 2 using:我有屏幕 1,我从中导航到屏幕 2:
navigation.navigate('Screen2')
From this screen, I would like to go to the previous one, which simple:从这个画面,我想把 go 转到上一个,这很简单:
navigation.goBack()
However I'm wondering how can I pass some data back to Screen1?但是我想知道如何将一些数据传递回 Screen1? Something like wouldn't work navigation.goBack({ myData: 'something' })
so I'm wondering what is the recommended way to do this in general?像这样的东西不起作用navigation.goBack({ myData: 'something' })
所以我想知道一般推荐的方法是什么?
You can solve it with 2 ways : 您可以通过两种方式解决它:
1 : Using navigation method 1:使用导航方法
Pass a method when you are calling that screen through navigation : 通过导航调用该屏幕时传递方法:
this.props.navigation.navigate('Screen2', {
onGoBack: this.refresh,
});
refresh=(data)=> {
}
and when you press back, pass data like 当你按回来时,传递数据
this.props.navigation.state.params.onGoBack('123');
this.props.navigation.goBack();
2 : Using redux store 2:使用redux存储
If you are using redux in your application, just update redux store whenever user presses back button, and get store value in previous screen. 如果您在应用程序中使用redux,只需在用户按下后退按钮时更新redux store,并在前一个屏幕中获取存储值。
You can pass a callback (onSelect) like this: 您可以像这样传递回调(onSelect):
// SCREEN 1
import React from "react";
import { Button, Text, View } from "react-native";
class Screen1 extends React.Component {
state = { selected: false };
onSelect = data => {
this.setState(data);
};
onPress = () => {
this.props.navigate("Screen2", { onSelect: this.onSelect });
};
render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}
// SCREEN 2
import React from "react";
import { Button } from "react-native";
class Screen2 extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Using the navigation method Pass a method when you are calling that screen through navigation:使用导航方法通过导航调用该屏幕时传递一个方法:
this.props.navigation.navigate('Screen2', {
onGoBack: this.refresh,
});
refresh=(data)=> {
console.log(data)
}
and when you press back, pass data like当你按回时,传递数据,如
this.props.route.params.onGoBack('123');
this.props.navigation.goBack();
yes goback work for going previous screen to...and show our data call from api...goBack()是的 goback 工作,用于将前一个屏幕转到...并显示来自 api...goBack() 的数据调用
if you're using v2 or newer, another possibility is using the navigate
function, providing key
/ routeName
of the route you're going back to and the params
. 如果你使用v2或更新,另一种可能性是使用navigate
功能,提供key
/ routeName
你要回路线和的params
。 docs: https://reactnavigation.org/docs/en/navigation-actions.html#navigate docs: https : //reactnavigation.org/docs/en/navigation-actions.html#navigate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.