Как передать текущее состояние приложения на экран навигации по вкладкам - PullRequest
0 голосов
/ 26 марта 2020

Если я использую React Navigation v5, как лучше всего передать текущее состояние родительского компонента (в моем случае, основного приложения) через навигатор Tab и Stack на экран, который мне нужен? использовать текущее состояние в?

Следуя документации, я создал навигатор стека для каждой вкладки с соответствующими экранами.

Приложение. js содержит состояние, которое должно быть используется для нескольких вещей. Самое главное, он обеспечит счетчик значков в навигаторе вкладок, а также будет источником данных Flatlist на одном из экранов вкладок.

Как правильно подходить к получению состояния из приложения на всем пути вниз дочернему компоненту в навигаторе стека в навигаторе вкладок?

Приложение. 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>
  )
}

Ответы [ 2 ]

1 голос
/ 26 марта 2020

Вы можете передать некоторые начальные параметры на экран. Если вы не указали никаких параметров при переходе к этому экрану, будут использованы начальные параметры. Они также мелко сливаются с любыми параметрами, которые вы передаете. Начальные параметры можно указать с помощью initialParams prop:

Использование

<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]);
0 голосов
/ 13 апреля 2020

Моим решением было использование React's Context API.

BeaconContext. js - Новый

import React from 'react'

const BeaconContext = React.createContext()

export default BeaconContext

Приложение. js - Изменено

import BeaconContext from './path/to/BeaconContext'

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(){
    startObserver(updateTheArray)
  }

  componentWillUnmount(){
    stopObserver()
  }

  render(){
    return(
      // Wrap the nav container in the newly created context!!!

      <BeaconContext.Provider value = { this.state.neededArray }
        <NavigationContainer>
          <Tab.Navigator>
            <Tab.Screen
              name = "Home"
              component = { HomeStack }/>
            <Tab.Screen
              name = "About"
              component = { AboutStack }/>
            <Tab.Screen
              name = "Nearby"
              component = { NearbyStack }/>
          </Tab.Navigator>
        </NavigationContainer>
      </BeaconContext.Provider>
    )
  }
}

NearbyStack. js - Без изменений

const NearbyStackNav = createStackNav()

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

NearbyScreen. js - Изменено

import BeaconContext from './path/to/BeaconContext'

const NearbyScreen = () => {
  return(
    <View>
      //Wrap the component in the new context's consumer!!!

      <BeaconContext.Consumer>
      {
        context => <Text>{ context }</Text>
      }
      </BeaconContext.Consumer>
    </View>
  )
}
...