在 React Navigation 中更新另一个屏幕的状态 [英] Updating State of Another Screen in React Navigation

查看:64
本文介绍了在 React Navigation 中更新另一个屏幕的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 } }
})

我正在尝试通过设置中的按钮更新 Home 状态同时保持在同一屏幕上(不使用 this.props.navigation.navigate),但是在搜索了几个小时之后,我就是不知道该怎么做.

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.

如果没有像 Redux 这样的东西,这甚至可能吗?我最初决定使用 Redux 来解决这个问题,但是当我发现他们在本赛季放弃官方支持时,我决定不使用它.

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.

推荐答案

这可以通过使用 NavigationActions.setParams 实现,如下所示:

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);

请注意,您需要使用主屏幕键.然后在您的主屏幕中,您需要聆听不断变化的 navigation 道具并根据该变化采取行动.这可以通过添加 componentWillRecieveProps React 生命周期事件或使用 getDerivedStateFromProps 静态方法来实现.您的参数将在 this.props.navigation.state.params 下.

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.

看看这里

这篇关于在 React Navigation 中更新另一个屏幕的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆