在 React Native 应用程序上工作,收到此错误:
WARN Possible Unhandled Promise Rejection (id: 1): TypeError: setAuthenticated is not a function (it is undefined)
这是我的 AuthPage,其中调用了 setAuthenticated:
const AuthenticationPage = ( { setAuthenticated }) => {
const navigation = useNavigation();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [emailError, setEmailError] = useState(false);
const onChangeEmail = email => setEmail(email);
const onChangePassword = password => setPassword(password);
//NEW SHIT BELOW UNTIL SIMULATED LOGIN
// let setAuthenticated;
// if (route && route.params) {
// setAuthenticated = route.params.setAuthenticated;
// }
const handleFormSubmit = async () => {
const newPerson = {
email: email,
password: password
};
if (!email.includes('@')) {
setEmailError(true);
}
else {
const response = await fetch(`${process.env.EXPO_PUBLIC_NGROK_URL}/api/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newPerson),
});
if (response.ok) {
const data = await response.json()
console.log(authenticated)
setAuthenticated(true); // Set authenticated state to true
navigation.navigate('Restaurants', {
customer_id: data.customer_id,
}); // Navigate to HomeScreen
return;
}
}
// Simulating a successful login. You can replace this with your actual login logic.
}
这就是我在 app.js 中传递 setAuthenticated 的方式:
const [authenticated, setAuthenticated] = useState(false);
<Stack.Screen
name="Authentication"
component={AuthenticationPage}
initialParams={{ setAuthenticated }}
/>
我已经尝试了我能想到的所有方法,从检查路由参数、直接将其作为参数传递等等。handleFormSubmit 可以正确获取数据,并且接收数据没有任何问题,但是一旦它点击“ setAuthenticated(true)" ,它就死了。
根据React Navigation的路由documentation传递参数,你正确地传递了它,但尝试将它作为通常的组件属性接收。
要解决此问题,请将
AuthenticationPage
组件中的参数获取方式更改为如下所示:
const AuthenticationPage = ({ route }) => {
const { setAuthenticated } = route.params;
// Rest of the code
}