React Native表单提交POST API及输入值undefined、不可编辑字段处理
解决方案
问题1:获取输入值为undefined的修复
你仅声明了text一个state,但email、number对应的state完全缺失,且name的state未从userInfo初始化,导致未修改时值为undefined。需要为所有字段声明state并赋予初始值。
问题2:设置name/email不可编辑
给对应的TextInput添加editable={false}属性即可禁用编辑,同时因为不可编辑,无需绑定onChangeText。
完整修改后的代码
import { useState } from 'react'; import { View, Text, TextInput, Button, StyleSheet } from 'react-native'; export default function Signupfor(props) { const { userInfo, log } = props?.route?.params || {}; // 初始化所有表单字段的state,从userInfo取初始值,兜底空字符串避免undefined const [name, setName] = useState(userInfo?.user?.name || ''); const [email, setEmail] = useState(userInfo?.user?.email || ''); const [whatsappNumber, setWhatsappNumber] = useState(userInfo?.user?.number || ''); async function getdata() { // 收集表单数据,name和email可直接用userInfo的值(与state值一致) const formData = { name: userInfo?.user?.name || name, email: userInfo?.user?.email || email, whatsappNumber: whatsappNumber }; console.log('表单数据:', formData); // 提交POST API示例 try { const response = await fetch('你的API接口地址', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }); const result = await response.json(); console.log('提交成功:', result); // 可添加提交后的逻辑,如页面跳转、提示用户等 } catch (error) { console.error('提交失败:', error); } } return ( <View style={styles.prheight}> <View style={styles.form}> <Text style={styles.r}>One Last Step</Text> <TextInput style={styles.forminput} label="Name" value={userInfo?.user?.name || name} editable={false} // 设置不可编辑 /> <TextInput style={styles.forminput} label="Email" value={userInfo?.user?.email || email} editable={false} // 设置不可编辑 /> <TextInput style={styles.forminput} label="Whatsapp Number" keyboardType="numeric" value={whatsappNumber} onChangeText={setWhatsappNumber} maxLength={10} /> </View> <View style={styles.buttonw}> <Button color="#7743DB" title="Lets Go" onPress={getdata} /> </View> </View> ); } // 保留原有样式定义 const styles = StyleSheet.create({ prheight: {}, form: {}, r: {}, forminput: {}, buttonw: {} });
关键修改说明
- 补全所有表单字段的state声明,从
userInfo初始化值,同时用空字符串兜底避免undefined - 给name/email输入框添加
editable={false}属性禁用编辑 getdata中直接收集包含不可编辑字段的完整表单数据- 添加POST API提交的示例代码,包含基础的错误处理逻辑
- 使用可选链
?.避免userInfo为空时的报错问题
内容的提问来源于stack exchange,提问作者vivek kn
相关产品推荐
相关产品推荐

