简体   繁体   English

在React中单击按钮时将元素从一个数组推送到另一个数组?

[英]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.

相关问题 复制数组并将一个元素从另一数组推入每个副本 - Copy array and push one element from another array to every copy 如何将数组作为一个元素推入另一个数组 - How to push array into another array as one element 反应:另一个孩子从数组 map 触发按钮单击 - React: Trigger button click from array map by another child 在React setState中使用变量将元素从一个数组移动到另一个数组? - Using variables in React setState to move an element from one array to another? 单击时,将一个项目从一个数组推送到另一个,并根据数组中的项目更改文本 - On click, push one item from an an array to another, and change text dependent on items in array 当我在 Javascript 中单击提交按钮时,我们如何从一个表中弹出元素并将相同的元素推送到另一个表中? - How we can pop element from one table and push the same element in other table when i click the submit button in Javascript? 将解构的值从一个数组推送到另一个数组 - Push destructured values from one array to another 通过引用从一个数组推到另一个数组 - Push from one array to another by reference React - 从 100 个按钮数组中更改一个按钮的 state,并一键重置所有按钮的 state - React - change state of one button from 100 buttons array, and reset state of all buttons on one click 单击按钮从一个页面导航到另一个页面 - Navigate from one page to another on Button click
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM