反应导航 goBack()并更新父状态

我有一个页面,将呈现用户的名称,如果她/他登录,或“创建一个帐户”或“登录”选项,如果她/他没有。屏幕如下

enter image description here

他们可以导航到“登录”或“创建帐户”页面。成功登录或注册之后,它将导航到此页面并显示用户名。屏幕如下

enter image description here

目前,我将用户数据存储在 AsyncStorage中,我想在用户成功登录或注册后从页面重定向时更新这个字段。

我怎么才能做到呢?

有没有一种方法来传递参数从 navigate.goBack()和父可以监听参数和更新其状态?

172530 次浏览

You can pass a callback function as parameter when you call navigate like this:

  const DEMO_TOKEN = await AsyncStorage.getItem('id_token');
if (DEMO_TOKEN === null) {
this.props.navigation.navigate('Login', {
onGoBack: () => this.refresh(),
});
return -3;
} else {
this.doSomething();
}

And define your callback function:

refresh() {
this.doSomething();
}

Then in the login/registration view, before goBack, you can do this:

await AsyncStorage.setItem('id_token', myId);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();

Update for React Navigation v5:

await AsyncStorage.setItem('id_token', myId);
this.props.route.params.onGoBack();
this.props.navigation.goBack();

I was facing a similar issue, so here is how I solved it by going more into details.

Option one is to navigate back to parent with parameters, just define a callback function in it like this in parent component:

updateData = data => {
console.log(data);
alert("come back status: " + data);
// some other stuff
};

and navigate to the child:

onPress = () => {
this.props.navigation.navigate("ParentScreen", {
name: "from parent",
updateData: this.updateData
});
};

Now in the child it can be called:

 this.props.navigation.state.params.updateData(status);
this.props.navigation.goBack();

Option two. In order to get data from any component, as the other answer explained, AsyncStorage can be used either synchronously or not.

Once data is saved it can be used anywhere.

// to get
AsyncStorage.getItem("@item")
.then(item => {
item = JSON.parse(item);
this.setState({ mystate: item });
})
.done();
// to set
AsyncStorage.setItem("@item", JSON.stringify(someData));

or either use an async function to make it self-update when it gets new value doing like so.

this.state = { item: this.dataUpdate() };
async function dataUpdate() {
try {
let item = await AsyncStorage.getItem("@item");
return item;
} catch (e) {
console.log(e.message);
}
}

See the AsyncStorage docs for more details.

is there a way to pass param from navigate.goback() and parent can listen to the params and update its state?

You can pass a callback function as parameter (as mentioned in other answers).

Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect):

ViewA.js

import React from "react";
import { Button, Text, View } from "react-native";


class ViewA extends React.Component {
state = { selected: false };


onSelect = data => {
this.setState(data);
};


onPress = () => {
this.props.navigate("ViewB", { onSelect: this.onSelect });
};


render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}

ViewB.js

import React from "react";
import { Button } from "react-native";


class ViewB extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}


render() {
return <Button title="back" onPress={this.goBack} />;
}
}

Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617


Edit

For React Navigation v5

ViewB.js

import React from "react";
import { Button } from "react-native";


class ViewB extends React.Component {
goBack() {
const { navigation, route } = this.props;
navigation.goBack();
route.params.onSelect({ selected: true });
}


render() {
return <Button title="back" onPress={this.goBack} />;
}
}

I just used standard navigate function giving ViewA route name and passing the parameters, did exactly what goBack would have done.

this.props.navigation.navigate("ViewA",
{
param1: value1,
param2: value2
});

The best solution is using NavigationEvents. You don't need to create listeners manually.

Calling a callback function is not highly recommended. Check this example using a listener (Remember to remove all listeners from componentWillUnMount with this option).

Component A:

navigateToComponentB() {
const { navigation } = this.props
this.navigationListener = navigation.addListener('willFocus', payload => {
this.removeNavigationListener()
const { state } = payload
const { params } = state
//update state with the new params
const { otherParam } = params
this.setState({ otherParam })
})
navigation.push('ComponentB', {
returnToRoute: navigation.state,
otherParam: this.state.otherParam
})
}
removeNavigationListener() {
if (this.navigationListener) {
this.navigationListener.remove()
this.navigationListener = null
}
}
componentWillUnmount() {
this.removeNavigationListener()
}

Commponent B:

returnToComponentA() {
const { navigation } = this.props
const { routeName, key } = navigation.getParam('returnToRoute')
navigation.navigate({ routeName, key, params: { otherParam: 123 } })
}

For more details of the previous example: https://github.com/react-navigation/react-navigation/issues/288#issuecomment-378412411

For those who don't want to manage via props, try this. It will call everytime when this page appear.

Note* (this is not only for goBack but it will call every-time you enter this page.)

import { NavigationEvents } from 'react-navigation';


render() {
return (
<View style=\{\{ flex: 1 }}>
<NavigationEvents
onWillFocus={() => {
// Do your things here
}}
/>
</View>
);
}

If you are using redux you can create an action to store data and check the value in parent Component or you can use AsyncStorage.

But I think it's better to passing only JSON-serializable params, because if someday you want to save state of navigation, its not very easy.

Also note react-navigation has this feature in experimental https://reactnavigation.org/docs/en/state-persistence.html

Each param, route, and navigation state must be fully JSON-serializable for this feature to work. This means that your routes and params must contain no functions, class instances, or recursive data structures.

I like this feature in Development Mode and when I pass params as function I simply can't use it

First screen

updateData=(data)=>{
console.log('Selected data',data)
}


this.props.navigation.navigate('FirstScreen',{updateData:this.updateData.bind(this)})

Second screen

// use this method to call FirstScreen method
execBack(param) {
this.props.navigation.state.params.updateData(param);
this.props.navigation.goBack();
}

I would also use navigation.navigate. If someone has the same problem and also uses nested navigators, this is how it would work:

onPress={() =>
navigation.navigate('MyStackScreen', {
// Passing params to NESTED navigator screen:
screen: 'goToScreenA',
params: { Data: data.item },
})
}

With React Navigation v5, just use the navigate method. From the docs:

To achieve this, you can use the navigate method, which acts like goBack if the screen already exists. You can pass the params with navigate to pass the data back

Full example:

import React from 'react';
import { StyleSheet, Button, Text, View } from 'react-native';


import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';


const Stack = createStackNavigator();


function ScreenA ({ navigation, route }) {
const { params } = route;


return (
<View style={styles.container}>
<Text>Params: {JSON.stringify(params)}</Text>
<Button title='Go to B' onPress={() => navigation.navigate('B')} />
</View>
);
}


function ScreenB ({ navigation }) {
return (
<View style={styles.container}>
<Button title='Go to A'
onPress={() => {
navigation.navigate('A', { data: 'Something' })
}}
/>
</View>
);
}


export default function App() {
return (
<NavigationContainer>
<Stack.Navigator mode="modal">
<Stack.Screen name="A" component={ScreenA} />
<Stack.Screen name="B" component={ScreenB} />
</Stack.Navigator>
</NavigationContainer>
);
}


const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

This solution did it for me, according to the navigation site: https://reactnavigation.org/docs/function-after-focusing-screen/#re-rendering-screen-with-the-useisfocused-hook

import { useFocusEffect } from '@react-navigation/native';


useFocusEffect(
React.useCallback(() => {
// YOUR CODE WHEN IT IS FOCUSED
return // YOUR CODE WHEN IT'S UNFOCUSED
}, [userId])
);

Easiest way to render the required components is by using useIsFocused hook.

React Navigation provides a hook that returns a boolean indicating whether the screen is focused or not. The hook will return true when the screen is focused and false when our component is no longer focused.

First import this in the required page where you want to navigate back. import { useIsFocused } from '@react-navigation/native';

Then, store this in any variable, and render components changes using React useEffect hook.

See code below or visit: Here

import React, { useState } from 'react';
import { useIsFocused } from '@react-navigation/core';


const HomeScreen = () => {
const isFocused = useIsFocused();
  

useEffect(()=>{
console.log("Focused: ", isFocused); //called whenever isFocused changes
}, [isFocused]);
    

return (
<View>
<Text> This is home screen! </Text>
</View>
)
}


export default HomeScreen;

I could not get any answer to work for my specific use case. I have a list being fetched from a database and a screen to add another list item. I wanted that once a user creates the item on the second screen, the app should navigate back to the first screen and show the newly added item in the list. Although the item was being added in the database, the list was not updating to reflect the change. The solution that worked for me: https://github.com/react-navigation/react-navigation.github.io/issues/191#issuecomment-641018588

So all I did was put this on the first screen and now the useEffect is triggered every time the screen is in focus or loses focus. import { useIsFocused } from "@react-navigation/native";

const isFocused = useIsFocused();
useEffect(() => {
// Code to run everytime the screen is in focus
}, [isFocused]);

Passing a callback through React Navigation in v5 throws a warning:

This can break usage such as persisting and restoring state

You can execute some code in screen A when you navigate back to it from Screen B in two easy ways:

First:

useEffect(() => {
const willFocusSubscription = navigation.addListener("focus", () => handleRefresh());
return () => willFocusSubscription
}, []);

This gets the job done. However, this method will be executed every time the screen is rendered. In order to only render it once when navigating back you can do the following:

Screen A:

import { DeviceEventEmitter } from "react-native";


useEffect(() => {
DeviceEventEmitter.addListener("userIsGoingBack", () => handleRefresh());
return () => DeviceEventEmitter.removeAllListeners("listingCreated");
}, []);

Screen B:

import { DeviceEventEmitter } from "react-native";


DeviceEventEmitter.emit("userIsGoingBack");

You can also pass some data alongside the emitted event to use in screen A if needed.

use Merge [take a look (react navigation 6.x)1

With react-navigation version 6 I implemented it by passing a parameter while navigating to another page then calling that parameter which is function beside goBack() function like this

Screen A :

navigation.navigate("Screen B", { refresh: () => getData() })

Screen B :

const { refresh } = route.params;


navigation.goBack();
refresh();