[英]push element from one array to another on button click in React?
I am trying to use the method.contact() to push on element in my old_array to my new_array.我正在尝试使用 method.contact() 将我的 old_array 中的元素推送到我的 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.所以你可以看到每个元素都有一个单独的 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:
(我从 API 获取 i.map() 到我的 old_array 的数据)我的 function 看起来像这样:
´´´ '''
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:这就是我想要我的 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()
在您的问题中,您到处都在使用
contact()
,我认为JS中的数组没有这样的function :),应该是concat()
Second:第二:
You can use ES6 for lower code, something like this:您可以将 ES6 用于较低的代码,如下所示:
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>
))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.