问题
import { createStackNavigator, createDrawerNavigator } from 'react-navigation'
import { Button, Text } from 'react-native'
import React, { Component } from 'react'
// Components
class Home extends Component {
constructor(props) {
super(props)
this.state = {value: 1}
}
render() {
return (<Text>{this.state.value}</Text>)
}
}
class Settings extends Component {
_press = function () {
// Update Home's state here
}
render() {
return (<Button title='Update Home' onPress={this._press.bind(this)}></Button>)
}
}
// Navigation
const homeNavigator = createStackNavigator({
HomeScreen: {screen: Home}
})
const settingsNavigator = createStackNavigator({
SettingsScreen: {screen: Settings}
})
const drawerScreens = createDrawerNavigator({
Home: homeNavigator,
Settings: settingsNavigator
})
export default createStackNavigator({
drawer: { screen: drawerScreens, navigationOptions: { header: null } }
})
I am trying to update the state of Home from my button in Settings while staying on the same screen (not using this.props.navigation.navigate
), but after searching for hours and hours I just cannot figure out how to do it.
Is this even possible without something like Redux? I initially decided to use Redux to solve this problem, but when I found out they're dropping official support this season, I decided against it.
回答1:
This is possible by using NavigationActions.setParams
as follows:
import { NavigationActions } from 'react-navigation';
const setParamsAction = NavigationActions.setParams({
params: { value: 2 },
key: 'screen-123',
});
this.props.navigation.dispatch(setParamsAction);
Note that you'll need to use the Home screen key.
Then in your Home screen you'll need to listen to the changing navigation
prop and act upon that change. This can be achieved by adding the componentWillRecieveProps
React lifecycle event or with the getDerivedStateFromProps
static method.
Your params will be under this.props.navigation.state.params
.
Take a look here
来源:https://stackoverflow.com/questions/53032782/updating-state-of-another-screen-in-react-navigation