首页 > 解决方案 > 如何将应用程序的当前状态传递到选项卡导航屏幕

问题描述

如果我使用的是 React Navigation v5,将父组件(在我的情况下是主应用程序)的当前状态通过选项卡和堆栈导航器向下传递到我想使用的屏幕的最佳方法是什么目前处于什么状态?

根据文档,我为每个包含相应屏幕的选项卡创建了一个堆栈导航器。

App.js 包含一个需要用于一些事情的状态。最重要的是,它将在选项卡导航器上提供徽章计数,并成为其中一个选项卡屏幕上的平面列表数据的来源。

将状态从 App 一直到选项卡导航器中堆栈导航器中的子组件的正确方法是什么?

应用程序.js

const Tab = createBottomTabNavigator()

export default class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      neededArray: []
    }
  }

  const updateTheArray = (newArray) => {
    this.setState({
      neededArray: newArray
    })
  }

  componentDidMount(){
    //Listener that searches for nearby bluetooth beacons and updates the array with the passed function
    startObserver(updateTheArray)
  }

  componentWillUnmount(){
    stopObserver()
  }

  render(){
    return(
      <NavigationContainer>
        <Tab.Navigator>
          <Tab.Screen
            name = "Home"
            component = { HomeStack }/>
          <Tab.Screen
            name = "About"
            component = { AboutStack }/>

          //The Stack that contains the screen that I need to use the App's state in
          <Tab.Screen
            name = "Nearby"
            component = { NearbyStack }/>
        </Tab.Navigator>
      </NavigationContainer>
    )
  }
}

NearbyStack.js

//This stack holds the screen that I need to use the App's state in

const NearbyStackNav = createStackNav()

const NearbyStack = () => {
  return(
    <NearbyStackNav.Navigator>
      <NearbyStackNav.Screen
        name = "Nearby"
        component = { NearbyScreen }
      />
    </NearbyStackNav.Navigator>
  )
}

NearbyScreen.js

//The screen that I want to use the App's state in
const NearbyScreen = () => {
  return(
    <View>
      <FlatList
        //Where I would like to use the App's state
      />
    </View>
  )
}

标签: react-nativereact-navigationreact-navigation-v5

解决方案


您可以将一些初始参数传递给屏幕。如果您在导航到此屏幕时未指定任何参数,则将使用初始参数。它们也与您传递的任何参数浅合并。可以使用initialParamsprop 指定初始参数:

用法

<Tab.Screen
            name = "Nearby"
            component = { NearbyStack }
            initialParams={{ arrayItem: this.state.neededArray }}
 />

NearbyScreen.js

React.useEffect(() => {
    if (route.params?.arrayItem) {
      // Post updated, do something with `route.params.arrayItem`
      // For example, send the arrayItem to the server
    }
  }, [route.params?.arrayItem]);

推荐阅读