Tengo una variable useState que tiene una matriz de objetos JSON, y estoy tratando de hacer que los campos de texto se representen y actualicen dinámicamente con onChangeText, pero tengo un pequeño problema con esto.
Cuando agrego console.log(index) a updateHashtags, dice que no está definido y no puedo entender qué estoy haciendo mal o qué puedo hacer para que esto funcione. En teoría, el índice debería ser un número estático para cada campo de texto. Entonces, el primer campo de texto tendría hashtags[0] como su valor y usaría '0' como índice para actualizar el estado de los hashtags.
Cuando uso: console.log('index',index); dentro de updateHashtags , obtengo: index undefined
Aquí está el código:
const updateHashtags = (text, index) => { let ht = hashtags; ht[index].name = text; setHashtags(ht); } const hashtagElement = ( <> <Text style={styles.plainText} >Set Your Values:</Text> <Text style={styles.instructionsText} >This is what other users use to search for you.</Text> {hashtags.map((e,index) => <TextInput placeholder='value' key={e.name + index} value={hashtags[index].name} onChangeText={(text,index) => updateHashtags(text,index)} style={styles.textInput} /> )} <TouchableOpacity onPress={() => { let ht = hashtags; let newht = { name: '', weight: 0, }; ht[ht.length] = newht; setHashtags(ht); }} > <Ionicons name="add-circle-outline" size={40} color={'black'} /> </TouchableOpacity> </> );Tal vez las funciones onChangeText no obtengan el parámetro de índice.
Pruébalo así:
// we are getting index from here {hashtags.map((e,index) => <TextInput placeholder='value' key={e.name + index} value={hashtags[index].name} // so no need of taking index from param here onChangeText={(text) => updateHashtags(text,index)} style={styles.textInput} /> )}También para sus funciones updateHashTags considere esto en lugar:
const updateHashtags = (text, index) => { // doing it this way ensures your are editing updated version of state setHashtags((state) => { let ht = state; ht[index].name = text; return ht; }); }