首页 > 解决方案 > 从 React 中的数组中删除项目时出现意外行为

问题描述

我已经到处寻找答案,但我只需要一些人的帮助。

我有一个简单的表单,用户可以在其中添加其他字段。用户还可以删除不再相关的字段。

这是我遇到问题的删除字段。

这些字段是从组件状态中的数组呈现的,但是当我尝试从数组中删除一个项目时,它始终是数组中被删除的最后一个项目。

import React, { Component } from "react";

class Form_newPriority extends Component {
  constructor(props) {
    super(props);
    this.state = {
      listName: "",
      rows: [{ id: 1, fieldValue: "" }],
    };
  }

  addrow = () => {
    const rows = [...this.state.rows];
    rows.push({
      id: rows.length + 1,
      fieldValue: "",
    });
    this.setState({ rows: rows });
  };

  removeRow = (idx) => {
    const rows = [...this.state.rows];
    rows.splice(idx, 1);
    this.setState({ rows: rows });
  };

  render() {
    return (
      <div>
        <input
          className="w-full bg-white border border-alice px-4 py-2 mb-1 h-12 rounded-lg"
          type="text"
        ></input>
        <h2>Items:</h2>
        {this.state.rows.map((row, idx) => {
          return (
            <React.Fragment>
              <input
                className="w-half bg-white border border-alice px-4 py-2 mb-4 mr-4  h-12 rounded-lg"
                key={idx}
                type="text"
                placeholder={idx}
              ></input>
              <button
                className="mb-4 text-red-700 inline-block"
                onClick={() => {
                  this.removeRow(idx);
                }}
              >
                Remove
              </button>
            </React.Fragment>
          );
        })}
        <button
          className="bg-alice hover:bg-gray-400 text-c_base text-sm font-bold py-1 px-2 rounded block mr-4"
          onClick={this.addrow}
        >
          Add row
        </button>
      </div>
    );
  }
}

export default Form_newPriority;

我也试过

rows.filter()

但这会产生相同的结果。

我对 JS 和 React 还很陌生,所以我在这里做了一些愚蠢的事情吗?

标签: javascriptreactjs

解决方案


看起来它删除了最后一个元素,因为您使用index的是身份。

当您使用增量id时,它更有意义

例子

const { Component, useState, useEffect } = React;

class Form_newPriority extends Component {
  constructor(props) {
    super(props);
    this.state = {
      listName: "",
      counter: 1,
      rows: [{ id: 1, fieldValue: "" }],
    };
  }

  addrow = () => {
    const rows = [...this.state.rows];
    const counter = this.state.counter + 1;
    rows.push({
      id: counter,
      fieldValue: "",
    });
    this.setState({ counter, rows });
  };

  removeRow = (idx) => {
    const rows = [...this.state.rows];
    rows.splice(idx, 1);
    this.setState({ rows: rows });
  };

  render() {
    return (
      <div>
        <input
          className="w-full bg-white border border-alice px-4 py-2 mb-1 h-12 rounded-lg"
          type="text"
        ></input>
        <h2>Items:</h2>
        {this.state.rows.map((row, idx) => {
          return (
            <React.Fragment key={row.id}>
              <input
                className="w-half bg-white border border-alice px-4 py-2 mb-4 mr-4  h-12 rounded-lg" 
                type="text"
                placeholder={row.id}
              ></input>
              <button
                className="mb-4 text-red-700 inline-block"
                onClick={() => {
                  this.removeRow(idx);
                }}
              >
                Remove
              </button>
            </React.Fragment>
          );
        })}
        <button
          className="bg-alice hover:bg-gray-400 text-c_base text-sm font-bold py-1 px-2 rounded block mr-4"
          onClick={this.addrow}
        >
          Add row
        </button>
      </div>
    );
  }
}

ReactDOM.render(
    <Form_newPriority />,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>


推荐阅读