React Native:传递给子组件的setAuthenticated未被识别为函数
解决React Native中
setAuthenticated is not a function错误 错误原因
你通过Stack.Screen的initialParams传递了setAuthenticated函数,但在AuthenticationPage组件里直接尝试从根props解构获取它——实际上这个函数是存在于route.params对象里的,不是组件的直接props,所以导致未定义。
修复步骤
- 在AuthPage组件中获取route对象:使用React Navigation的
useRoute钩子拿到当前路由的参数。 - 从route.params中取出setAuthenticated:确保正确获取传递过来的函数,同时做兜底处理避免params为空的情况。
修改后的AuthenticationPage代码
import { useNavigation, useRoute } from '@react-navigation/native'; import { useState } from 'react'; const AuthenticationPage = () => { const navigation = useNavigation(); const route = useRoute(); // 从route.params中获取setAuthenticated,兜底防止params不存在 const { setAuthenticated } = route.params || {}; const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [emailError, setEmailError] = useState(false); const onChangeEmail = email => setEmail(email); const onChangePassword = password => setPassword(password); const handleFormSubmit = async () => { const newPerson = { email, password }; if (!email.includes('@')) { setEmailError(true); return; } try { 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(); // 确保setAuthenticated存在再调用 if (typeof setAuthenticated === 'function') { setAuthenticated(true); } navigation.navigate('Restaurants', { customer_id: data.customer_id, }); } } catch (err) { // 捕获Promise错误,避免Unhandled Promise Rejection警告 console.error('登录请求失败:', err); } }; // 组件的其他渲染逻辑... };
额外注意事项
- 移除了代码中未定义的
console.log(authenticated),避免额外错误。 - 给
handleFormSubmit添加了try/catch,捕获fetch请求可能出现的Promise错误,解决Unhandled Promise Rejection警告。 - 调用
setAuthenticated前增加了类型检查,进一步避免报错。
内容的提问来源于stack exchange,提问作者d3fk0nn
相关产品推荐
相关产品推荐

