react-native - 如何将应用程序的当前状态传递到选项卡导航屏幕
问题描述
如果我使用的是 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>
)
}
解决方案
您可以将一些初始参数传递给屏幕。如果您在导航到此屏幕时未指定任何参数,则将使用初始参数。它们也与您传递的任何参数浅合并。可以使用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]);
推荐阅读
- memory-management - TLB 是否仅包含单个进程的条目?
- android - 如何解决 Android 应用程序的 audeince 网络中的质量检查问题?
- ios - FileManager.enumerator 在 ios 设备上测试时返回 nil
- javascript - D3图表图例标签重叠
- javascript - 如何用键渲染对象?
- android - 如何删除预期的 BEGIN_OBJECT 但在改造 2 中的第 1 行第 1 列路径 $ 字符串?
- listview - 如何制作可编辑的 ListView 项目?
- javascript - 如何在 div 上有效地声明事件
- android - Android Studio 将对象保存到 SQLite 数据库中
- react-native - 如何让我的 Picker 在 React Native 中垂直对齐?