How to update the array - ReactNative

廉价感情. 提交于 2019-12-12 03:39:35

问题


What I'm trying to achieve is an Array like this

infos = [{type: 'phone', val: '2222222'}
           {type: 'email', val: 'abc@abc.com'}]

Here is the state

constructor(props) {
super(props);
this.state = {
  rows: [], //this is used for the add component 
  contactDetails: [{type: '', val: ''}], // where i will add the values 
};
}

So I have a two TextInput

<View>
  <TextInput label='Type'/>
  <TextInput label='Details'/>
</View>

This View can be dynamically added when a button is clicked and can also be deleted. Here is my code for the add and delete button:

addRow(){
 this.state.rows.push(index++)
 this.setState({ rows: this.state.rows })
}

deleteRow(key){
 this.state.rows.splice(key, 1)
 this.setState({ rows: this.state.rows })
}

<TouchableOpacity onPress={ this.addRow.bind(this) } >
   <Text style={{textAlign: 'center',}}>Add</Text>
</TouchableOpacity>

 ...

 <TouchableOpacity  onPress={ () => this.deleteRow(i) } >
   <Image source={require('./../img/delete.png')} style={{width:32, height: 32 }} />
 </TouchableOpacity>

How can I get the value of it correctly and add it to my Array? Thank you.


Update

In my TextInput I tried doing this

<TextInput 
                    onChangeText={(text)=>{
                      let cd = this.state.contactDetails;
                      cd[i].val = text ;
                      this.setState({cd});

                    }}
                    value={this.state.contactDetails[i]}
                    label='Details' 
                    />

but I'm always having an error undefined is not an object (evaluating 'cd[i].val = text')


回答1:


You can't manipulate state by declaring this.state.rows.push(index++), but you must do it with concat() and return the value to new variable. For instance (I actually don't know what index represents in your case, but let's give it a try:

addRow() {
 const rows = this.state.rows.concat(index++)
 this.setState({rows})
}

Here's a working example what I assume you're trying to achieve: https://snack.expo.io/HySVtag6g




回答2:


In my state, I added an array like this

info: {
    type: '',
    val: '',
  }

And then I added this to my addRow

addRow(){
//add new array in contactDetails
var arrayvar = this.state.contactDetails.slice()
arrayvar.push(this.state.info)
this.setState({ contactDetails: arrayvar })

//add new component row
this.state.rows.push(index++);
this.setState({ rows: this.state.rows});
}

Where every time the add button is clicked the Array named info with empty values will be added to the contactDetails and then I update the values of the added array.



来源:https://stackoverflow.com/questions/43197537/how-to-update-the-array-reactnative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!