在 React 中从数组中删除项目时出现意外行为

2023-12-30

我到处寻找这个问题的答案,但我只需要一些人的帮助。

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

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

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

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 相当陌生,所以我在这里做了一些愚蠢的事情吗?


它可能看起来像删除了最后一个元素,因为您正在使用index作为身份。

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

Example

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 React 中从数组中删除项目时出现意外行为 的相关文章

随机推荐