React Native 使用navigation.goBack()时如何将数据发送回上一个场景?

fzwojiic  于 2023-05-23  发布在  React
关注(0)|答案(6)|浏览(325)

我有屏幕1,我使用以下命令导航到屏幕2:

navigation.navigate('Screen2')

从这个屏幕,我想去前一个,其中简单:

navigation.goBack()

但是,我想知道如何将一些数据传递回Screen1?像wouldn't work navigation.goBack({ myData: 'something' })这样的东西,所以我想知道通常推荐的方法是什么?

um6iljoc

um6iljoc1#

你可以用两种方法来解决它:

1:使用导航方式

通过导航调用该屏幕时传递一个方法:

this.props.navigation.navigate('Screen2', {
  onGoBack: this.refresh,
});

refresh=(data)=> {

}

当你按下返回键时,

this.props.navigation.state.params.onGoBack('123');
this.props.navigation.goBack();

2:使用redux store

如果你在应用程序中使用redux,只要在用户按下后退按钮时更新redux store,并在前一个屏幕中获取store值。

jmp7cifd

jmp7cifd2#

你可以像这样传递一个回调(onSelect):
屏幕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>
    );
  }
}

屏幕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} />;
  }
}
zlhcx6iw

zlhcx6iw3#

使用导航方法在通过导航调用该屏幕时传递一个方法:

this.props.navigation.navigate('Screen2', {
  onGoBack: this.refresh,
});

refresh=(data)=> {
   console.log(data)
}

当你按下返回键时,

this.props.route.params.onGoBack('123');
this.props.navigation.goBack();
tsm1rwdh

tsm1rwdh4#

// PreviousScreen.js
const PreviousScreen = () => {
  const handleData = (data) => {
    // Handle the received data here
    console.log('Received data:', data);
  };

  // Navigate to the next screen and pass the callback function as a parameter
  const goToNextScreen = () => {
    navigation.navigate('NextScreen', { callback: handleData });
  };

  // ...
};/
// NextScreen.js
const NextScreen = ({ navigation, route }) => {
  // Retrieve the callback function from the navigation parameters
  const callback = route.params?.callback;

  // Call the callback function with the data you want to send back
  const sendDataToPreviousScreen = () => {
    const data = 'Hello from NextScreen!';
    callback && callback(data); // Make sure the callback exists before calling it
    navigation.goBack();
  };

  // ...
};
fcg9iug3

fcg9iug35#

如果您使用的是v2或更新版本,另一种可能性是使用navigate函数,提供您要返回的路由的key/routeNameparams。文档:https://reactnavigation.org/docs/en/navigation-actions.html#navigate

klsxnrf1

klsxnrf16#

是的,goback用于将上一个屏幕转到...并显示来自API的数据调用...goBack()

相关问题