React Native Stack Navigator使用状态



我尝试从MyStack组件共享状态数据。第二个数据的组成部分总是更改,但第一个屏幕没有你能告诉我这是怎么回事吗??我必须改变什么。谢谢:D

import React ,{ useState } from 'react';
import { Button, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function First({route , navigation}) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title={route.params.count.toString()}
onPress={() => navigation.navigate('Second')}/>
</View>
);
} 
function Second({route , navigation }) {
route.params.setCount(route.params.count + 1);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title={route.params.count.toString()}
onPress={() => { navigation.goBack()}}
/>
</View>
);
}

const Stack = createStackNavigator();
function MyStack() {
const [count, setCount] = useState(0);
return (
<Stack.Navigator>
<Stack.Screen name="First" component={First} initialParams={{ count: count , setCount  : setCount }}/>
<Stack.Screen name="Second" component={Second} initialParams={{ count: count ,setCount  : setCount}}/>
</Stack.Navigator>
);
}
export default function App(props) {
return (
<NavigationContainer>
<MyStack props={props}/>
</NavigationContainer>
);
}

以上不起作用的原因是FirstScreen没有被重新渲染。渲染屏幕后,无法动态更改初始参数。即使你的屏幕2工作不正常,你也可以设置它,但当你重新访问屏幕时,你会看到更新的值。

解决这个问题的方法是使用上下文api,您可以使用它来跳过导航参数。

并且总是使用useEffect之类的钩子或buttonclick来更新上下文,否则它会不断重新渲染,从而导致错误。代码如下所示。

import React, { useState, createContext, useContext } from 'react';
import { Button, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const appContext = createContext();
function First({ route, navigation }) {
const context = useContext(appContext);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title={context.count.toString()}
onPress={() => navigation.navigate('Second')}
/>
</View>
);
}
function Second({ route, navigation }) {
const context = useContext(appContext);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title={context.count.toString()}
onPress={() => {
navigation.goBack();
}}
/>
<Button
title="Add to Count"
onPress={() => {
context.setCount(context.count + 1);
}}
/>
</View>
);
}
const Stack = createStackNavigator();
function MyStack() {
const [count, setCount] = useState(0);
const state = { count, setCount };
return (
<appContext.Provider value={state}>
<Stack.Navigator>
<Stack.Screen name="First" component={First} />
<Stack.Screen name="Second" component={Second} />
</Stack.Navigator>
</appContext.Provider>
);
}
export default function App(props) {
return (
<NavigationContainer>
<MyStack props={props} />
</NavigationContainer>
);
}

相关内容

  • 没有找到相关文章

最新更新