Estoy aprendiendo reaccionar nativo, he estado recibiendo este error setState no es una función en reaccionar nativo Busqué mucho pero nada fue lo suficientemente útil.
He creado este código simplificado para mostrar el problema.
import React, { useState } from "react"; import { Text, View, Button } from "react-native"; const Test = ({ Test1 }) => { return ( <Button onPress={() => { Test1.setState(true); }} /> ); }; const Test1 = () => { const [state, setState] = useState(false); if (state) { return <Text>Test Working</Text>; } else { return <Text>Test Not Working</Text>; } }; const App = () => { return ( <View> <Test Test1={Test1} /> </View> ); }; export default App; este es el error: TypeError: Test1.setState is not a function
Por favor ayúdame a arreglar esto.
Los estados se pueden transferir a otro componente solo como accesorios. Debe llamar al componente Test1 desde la aplicación y al componente Test desde Test1, luego puede pasar los accesorios a Test desde Test1. Por esto, no necesita mover el estado a otro componente. no puede pasar ningún componente como accesorios y acceder al estado o métodos desde allí. Puedes probar este código:
import React, { useState } from "react"; import { Text, View, Button } from "react-native"; const Test = ({ setState}) => { return ( <Button onPress={() => { setState(true); }} /> ); }; const Test1 = () => { const [state, setState] = useState(false); if (state) { return <Text>Test Working</Text>; } else { return <Test setState={setState} />; } }; const App = () => { return ( <View> <Test1 /> </View> ); }; export default App;import React, { useState } from "react"; import { Text, View, Button } from "react-native"; const Test = ({ setState }) => { return ( <Button onPress={() => { setState(true); }} ); }; const Test1 = ({state}) => { if (state) { return <Text>Test Working</Text>; } else { return <Text>Test Not Working</Text>; } }; const App = () => { const [state, setState] = useState(false); return ( <View> <Test1 state={state} /> <Test setState={setState} /> </View> ); }; export default App;Hay dos problemas aquí.
Si desea administrar algún estado local en su componente de prueba, debe vivir en ese componente.