简体   繁体   中英

array.splice() deleting wrong element

I'm a beginner to react js and was wondering why the splice() method wasn't working properly for me. My method is here:

removePara = index => {
    let array = [...this.state.paras];
    for (let x = 0; x < this.state.count; x++) {
      try {
        if (array[x].props.id == index) {
          array.splice(x, 1);
        }
      } catch (e) {}
    }
    this.setState({ paras: array });
  };

So I'm passing an index, and if an element's id matches the index, the element is removed. I'v used a try-catch cause not all indexes are there (they might've been deleted through the same function). Here's and image of three elements: 在此处输入图片说明

I am pressing delete for middle one but this happens: 在此处输入图片说明

Instead of the second one getting deleted, the last one gets deleted. How do I fix this? I know that my button's onclick works fine. Full code below:

//index.js
const rootElement = document.getElementById("root");

class App extends React.Component {
  state = {
    paras: [],
    count: 0
  };

  addPara = () => {
    this.setState({
      paras: [
        ...this.state.paras,
        <Paragraph id={this.state.count++} remove={this.removePara} />
      ]
    });
  };

  removePara = index => {
    let array = this.state.paras.filter(e => e.props.id !== index);
    this.setState({ paras: array });
  };

  render() {
    return (
      <div>
        {this.state.paras}
        <div className="btn btn-warning" id="add" onClick={this.addPara}>
          Add Paragraph
        </div>
        <div name="count">{this.state.count}</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, rootElement);

//Paragraph.js
class Paragraph extends React.Component {
  render() {
    let style = {
      height: "150px",
      marginBottom: "10px"
    };

    return (
      <div className="paragraph" id={this.props.id}>
        <div className="row">
          <div className="col-sm-11">
            <textarea
              className="form-control"
              name={"paragraph" + this.props.id}
              placeholder="Put Paragraph Here"
              style={style}
              required
            ></textarea>
          </div>
          <div className="col-sm-1">
            <div
              className="btn btn-danger del-rotate"
              onClick={() => this.props.remove(this.props.id)}
            >
              &times;
            </div>
          </div>
        </div>
      </div>
    );
  }
}
<!--index.html-->
<html>

<head>
    <script type="application/javascript" src="../reactjs/react.js"></script>
    <script type="application/javascript" src="../reactjs/react-dom.js"></script>
    <script type="application/javascript" src="../reactjs/babel.js"></script>
    <link rel="stylesheet" type="text/css" href="../css/styles.css">
    <script src="../bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="../bootstrap/css/bootstrap.min.css">
    <script type="text/babel" src="Components/Paragraph.js"></script>
    <script type="text/babel" src="index.js"></script>
</head>

<body id="body">
    <div class="container-fluid">
        <br>
        <br>
        <div class="row">
            <div class="col-sm-1"></div>
            <div class="col-sm-10">
                <div align="center">
                    <h1>Write Article</h1>
                </div>
                <br>
                <form action="submit-article.php" method="POST">
                    <input class="form-control input-sm" type="text" placeholder="Enter Title" name="title"
                        style="width: 35%" autofocus required></input>
                    <br>
                    <div id="root"></div>
                    <br>
                    <input class="btn btn-success float-right" type="submit" value="Done">
                </form>
            </div>
        </div>
    </div>
</body>

</html>

But the element which matches the id gets deleted, like in the elements, its not there, but the input of the one that gets deleted just gets into another element. Like in the example above in the pictures

Probably the index you're passing is incorrect,

Array.filter would be more appropriate for this kind of task :

removePara = index => {
  let array = this.state.paras.filter(e => e.props.id !== index);
  this.setState({ paras: array });
};

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.

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