简体   繁体   English

从阵列中删除所选项目

[英]Remove selected item from array

I have a simple form, where I would like to remove the selected item on remove button click. 我有一个简单的表单,我想在其中单击“删除”按钮时删除所选的项目。 I'm partially removing the desired item, but if I remove the middle item, it also removes the last item. 我正在部分删除所需的项目,但是如果我删除中间的项目,它也会删除最后一个项目。 If I remove the first item, it removes the entire array. 如果删除第一项,它将删除整个数组。

Live example here 这里的例子

code here: 代码在这里:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: ["Saab", "Volvo", "BMW"],
      editMode: false,
      rulesTerm: ""
    };
  }

    handleInput = e => {
    let value = e.target.value;
    let name = e.target.name;
    console.log(name);
    console.log(value);

    this.setState(prevState => ({
      data: {
        ...prevState.data,
        [name]: value
      }
    }));
  };

  handleFormSubmit = e => {
    e.preventDefault();

    const { data } = this.state;
    console.log(data);
  };

  removeRule = (e, index) => {
    e.preventDefault();

    const { data } = this.state;
    console.log("removed", data.splice(index));

    this.setState({
      data: data,
      rulesTerm: ""
    });
  };

  render() {
     return (
       <div className="App">
        <div>
          {!this.state.editMode ? (
            <button onClick={() => this.setState({ editMode: true })}>
              edit
            </button>
          ) : (
            <div>
              <button onClick={() => this.setState({ editMode: false })}>
                cancel
               </button>
              <button onClick={this.handleFormSubmit}>submit</button>
            </div>
           )}
        </div>

        <React.Fragment>
          {this.state.data.map((rule, index) =>
            this.state.editMode ? (
              <form onSubmit={this.handleFormSubmit}>
                <React.Fragment>
                  <input
                    onChange={this.handleInput}
                    type="text"
                    placeholder="Cars"
                    name={rule}
                    defaultValue={rule}
                    key={index}
                  />
                  <button onClick={event => this.removeRule(event, index)}>
                    Remover
                  </button>
                </React.Fragment>
              </form>
            ) : (
              <p key={rule}> - {rule} </p>
            )
          )}
        </React.Fragment>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Any help? 有什么帮助吗? Thank you! 谢谢!

When using splice , you need to pass in the number of elements to delete. 使用splice ,您需要传递要删除的元素数量。

If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted. 如果省略deleteCount,或者其值等于或大于array.length-开始(即,如果等于或大于数组中剩余的元素数量,则从start开始),则所有从数组开始到结尾的所有元素都将被删除。

One solution would be to convert your deleting function into a curried function, which will first receive the index when called once, and then the event. 一种解决方案是将删除函数转换为咖喱函数,该函数将在调用一次后首先接收index ,然后再接收事件。

You can filter out your element using the callback version of setState and filtering out the element with the same index : 您可以使用setState的回调版本过滤出元素,并过滤出具有相同索引的元素:

removeRule = index => event => {
    this.setState(prev => ({
        data: prev.data.filter((el, i) => i !== index),
        rulesTerm: ""
    }));
};

You could also indicate your splice method that it only requires to remove a single element : 您还可以指示您的splice方法只需要删除一个元素即可:

removeRule = index => event => {
    this.setState(prev => ({
        data: prev.data.splice(index, 1),
        rulesTerm: ""
    }));
};

Your function binding in the JSX will now look like the following : 现在,您在JSX中的函数绑定如下所示:

<button onClick={this.removeRule(index)}>
    Remover
</button>

In your case I would use a filter, and pass the rule as an argument: 在您的情况下,我将使用过滤器,并将规则作为参数传递:

 <React.Fragment>
          {this.state.data.map((rule, index) =>
            this.state.editMode ? (
              <form onSubmit={this.handleFormSubmit}>
                <React.Fragment>
                  <input
                    onChange={this.handleInput}
                    type="text"
                    placeholder="Cars"
                    name={rule}
                    defaultValue={rule}
                    key={index}
                  />
                  <button onClick={event => this.removeRule(event, rule)}>
                    Remover
                  </button>
                </React.Fragment>
              </form>
            ) : (
              <p key={rule}> - {rule} </p>
            )
          )}
        </React.Fragment>

Than in your removeRule function: 比您的removeRule函数中:

removeRule = (e, rule) => {
    e.preventDefault();

    const { data } = this.state;
    const newData = data.filter(item => item !== rule);
    console.log("removed");

    this.setState({
      data: newData,
      rulesTerm: ""
    });
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM