I am trying to use the method.contact() to push on element in my old_array to my new_array. I have one button on each element in the array like this:
´´´
<li key={i}>
{{character.name} + "is" + {character.age} + "years old"}
<button onClick={this.addToNewArray}>Fav</button>
</li>
´´´
so as you can see each element got a seperate id. Now i want to click the button to push that element to a new array. (i get data from API that i.map() into my old_array) My function looks like this:
´´´
constructor(props){
super(props);
this.state = {
old_arary: [],
new_array: []
}
}
addToNewArray = () => {
let new_array = this.state.new_array.contact(this.state.old_array);
this.setState({ new_array: new_array})
}
´´´
This is where i want my output:
´´´
<li>
{this.state.new_array}
</li>
´´´
First:
in your question, you are using contact()
everywhere, and I think there is no such function for array in JS:), that should be concat()
Second:
You can use ES6 for lower code, something like this:
let new_array = [...this.state.new_array , ...this.state.old_array];
this.setState({ new_array });
Third:
Change this
<li>
{this.state.new_array}
</li>
To:
{
this.state.new_array.map((obj,index) => (
<li key={index}>
{obj.name}
</li>
))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.