React Native 状态未在堆栈内更新,Navigator

gopyfrb3  于 2023-03-31  发布在  React
关注(0)|答案(1)|浏览(150)

当屏面放置在<Stack.Navigator>内时,状态未更新

export default function App() {
    const Stack=createNativeStackNavigator()
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name='TestScreen' children={TestScreen}/>
            </Stack.Navigator> 
        </NavigationContainer>
    );
}

测试屏幕如下:

const TestScreen = () => {
    const [currentCell, setCurrentCell] = useState(1)
    return (
        <SafeAreaView>
            <Text>{currentCell}</Text>
            <Button
                title='change'
                onPress={()=>setCurrentCell(currentCell==1?2:1)}
            />
        </SafeAreaView>
    );
}

如果应用程序被替换为以下代码,则它可以工作

export default function App() {
    const Stack=createNativeStackNavigator()
    return (
        <NavigationContainer>
            <TestScreen/>
        </NavigationContainer>
    );
}

如何解决此问题?https://snack.expo.dev/@rujengelal/ashamed-edamame

bzzcjhmw

bzzcjhmw1#

正如@YoussoufOumar在评论中提到的,Stack.Screen需要一个component,而不是children

import { useState } from 'react';
import { Button, Text } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

export default function App() {
  const Stack = createNativeStackNavigator();

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="TestScreen" component={TestScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
const TestScreen = () => {
  const [currentCell, setCurrentCell] = useState(1);

  return (
    <SafeAreaView>
      <Text>{currentCell}</Text>
      <Button
        title="change"
        onPress={() => setCurrentCell(currentCell == 1 ? 2 : 1)}
      />
    </SafeAreaView>
  );
};

这里有一个小吃来测试它https://snack.expo.dev/@mohammed-handa/state-not-updating-inside-stack-navigator

相关问题