Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
Obtenga solo un valor indefinido de mi variable global configurada con Contexto

Tengo una aplicación React Native con dos páginas. En la primera página tengo un selector del que necesito los datos en la segunda página. Intento usar Contexto para hacer que el estado esté disponible globalmente, pero no lo hice funcionar hasta ahora porque solo obtengo tipos indefinidos en la posición donde quiero insertar el estado global y no el valor que se seleccionó del selector. No obtengo ningún error, pero el campo donde se debe representar el valor del selector está vacío.

Archivo del que quiero obtener el estado:

 const FirstFile = () => { const [selectedValueRound, setSelectedValueRound] = useState("10 rounds"); return ( <View> <RoundContext.Provider value={[selectedValueRound, setSelectedValueRound]} > <View> <Picker selectedValue={selectedValueRound} onValueChange={(itemValue, itemIndex) => setSelectedValueRound(itemValue) } > <Picker.Item label="1 round" value="0"></Picker.Item> <Picker.Item label="2 rounds" value="1"></Picker.Item> </Picker> </View> </RoundContext.Provider> </View> ); };

Archivo de contexto:

 export const RoundContext = createContext(false);

Archivo de navegación donde envuelvo mi contexto

 const Stack = createNativeStackNavigator(); const {selectedValueRound, setSelectedValueRound} = useContext(RoundContext); const MyStack = () => { return ( <RoundContext.Provider value={[selectedValueRound, setSelectedValueRound]}> <NavigationContainer> <Stack.Navigator> <Stack.Screen name="FirsFile" component={FirsFile} /> <Stack.Screen name="SecondFile" component={SecondFile} /> </Stack.Navigator> </NavigationContainer> </RoundContext.Provider> ); };

Archivo donde trato de insertar el valor global:

 const SecondFile = () => { const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext); return ( <View> <Text>{selectedValueRound}</Text> </View> ); }; export default SomeFile;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

También debe definir el proveedor de contexto y envolver su aplicación en él.

 export const RoundContextProvider = ({children}) => { const stateTuple = useState(false); return <RoundContext.Provider value={stateTuple}>{children}</RoundContext.Provider>; }
 <RoundContextProvider> <YourApp/> </RoundContextProvider>

luego puede usarlo como lo describió en la pregunta: const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);

about 4 years ago · Juan Pablo Isaza Relatório

0

Debe declarar el state y el proveedor de contexto en el componente principal superior. Los niños solo deben consumir los valores del contexto.

El componente padre

 const MyStack = () => { const [selectedValueRound, setSelectedValueRound] = useState("10 rounds"); const contextValue = useMemo( () => [selectedValueRound, setSelectedValueRound], [selectedValueRound] ); return ( <RoundContext.Provider value={contextValue}> <NavigationContainer> <Stack.Navigator> <Stack.Screen name="FirsFile" component={FirsFile} /> <Stack.Screen name="SecondFile" component={SecondFile} /> </Stack.Navigator> </NavigationContainer> </RoundContext.Provider> ); };

Tenga en cuenta que utilicé useMemo para evitar pasar una nueva matriz al contexto cuando selectedValueRound no cambió.

Los niños

 const FirstFile = () => { const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext); return ( <View> <View> <Picker selectedValue={selectedValueRound} onValueChange={itemValue => setSelectedValueRound(itemValue)} > <Picker.Item label="1 round" value="0"></Picker.Item> <Picker.Item label="2 rounds" value="1"></Picker.Item> </Picker> </View> </View> ); };
 const SecondFile = () => { const [selectedValueRound] = useContext(RoundContext); return ( <View> <Text>{selectedValueRound}</Text> </View> ); };
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda