You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native添加用户输入至state数组时遇TypeError错误求助

问题分析与修复方案

错误原因

你遇到的TypeError: undefined is not an object (evaluating 'userGoals.map')错误,根源在于addGoalHandler函数中,setUserGoals的回调函数没有返回新的数组。当点击按钮时,回调执行后默认返回undefined,导致userGoals状态被更新为undefined,而undefined没有map方法,因此触发报错。

修复步骤

修改addGoalHandler函数,确保回调返回新的数组,同时可以添加输入校验和清空输入框的逻辑,提升用户体验:

function addGoalHandler() {
  // 过滤空输入,避免添加空目标
  if (!enteredGoalText.trim()) return;
  
  setUserGoals((currentUserGoals) => {
    // 必须返回新的数组,更新state
    return [...currentUserGoals, enteredGoalText.trim()];
  });
  // 添加后清空输入框
  setEnteredGoalText('');
};

完整修复后的代码

import { StatusBar } from 'expo-status-bar';
import { useState } from 'react';
import { Button, StyleSheet, Text, TextInput, View, ScrollView } from 'react-native';

export default function App() {

  const [enteredGoalText, setEnteredGoalText] = useState('');
  const [userGoals, setUserGoals] = useState([]);

  function addGoalHandler() {
    if (!enteredGoalText.trim()) return;
    
    setUserGoals((currentUserGoals) => {
      return [...currentUserGoals, enteredGoalText.trim()];
    });
    setEnteredGoalText('');
  };

  function goalInputHandler(enteredText) {
    setEnteredGoalText(enteredText);
  };


  return (
    <View style={styles.appContainer}>
      <View style={styles.inputContainer}>
          <TextInput 
            style={styles.textInput}
            placeholder="Enter your goal"
            onChangeText={goalInputHandler}
            value={enteredGoalText} // 添加value绑定,确保输入框状态受控
          />
          <Button title="Add Goal" onPress={addGoalHandler}/>
      </View>
      <View style={styles.goalContainer} >
        <ScrollView>
          {userGoals.map((goal, index) => {
            return (
              <View style={styles.goalItem} key={index}>
                <Text style={styles.goalText}>{goal}</Text>
              </View>
            )
          })}
          </ScrollView>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  appContainer: {
    paddingTop: 50,
    paddingHorizontal: 16,
    borderWidth: 5,
    flex : 1,
  },
  inputContainer: {
    flex: 1,
    flexDirection: "row", 
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingBottom: 24,
    borderBottomWidth: 1,
    borderBottomColor: 'gray',
  },
  textInput: {
    borderColor: 'gray',
    borderWidth: 1,
    width: '70%',
    marginRight: 8,
    padding: 8
  }, 
  goalContainer: {
    flex: 8
  },
  goalItem: {
    margin: 8,
    padding: 8,
    borderRadius: 6,
    backgroundColor: 'purple'
  },
  goalText: {
    color: 'white'
  }
});

额外说明:给TextInput添加了value={enteredGoalText}绑定,让输入框成为受控组件,确保输入状态和enteredGoalText完全同步。

内容的提问来源于stack exchange,提问作者ForeverLearner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:45:44