如何在 reactjs 中正确追加记录而不互相替换

How to properly append records without replacing each other in reactjs

我的数据库中有一些记录。该代码显示 table 上的第一条记录。当我想通过 appendMore 按钮将第二条记录附加到第一条记录时。第二条记录显示第一条记录。请如何正确地将第二条或下一条附加到第一条记录。这是我到目前为止的努力

import React from "react";
import axios from "axios";
import "./App.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      persons: [],
    };
    this.appendMore = this.appendMore.bind(this);
  }

  componentDidMount() {
    const url = "http://localhost/data/first_record.php";
    axios
      .get(url)
      .then((response) => response.data)
      .then((data) => {
        this.setState({ persons: data });
        console.log(this.state.persons);
        //alert(data);
        console.log(data);
      });
  }

  appendMore() {
    const url = "http://localhost/data/second_record.php";
    axios
      .get(url)
      .then((response) => response.data)
      .then((data) => {
        this.setState({ persons: data });
        // const persons = [...this.state.persons];

        console.log(this.state.persons);
        //alert(data);
        console.log(data);
      });
  }

  render() {
    //const { } = this.state;
    return (
      <div>
        <h1>Contact</h1>
        <table border="1" width="100%">
          <tbody>
            <tr>
              <th>id</th>
              <th>Name</th>
            </tr>

            {this.state.persons.map((contact, key) => (
              <tr key={key}>
                <td>{contact.id}</td>
                <td>{contact.name}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <span onClick={this.appendMore}>Append More</span>
      </div>
    );
  }
}

export default App;

这将按预期合并两个数组:

this.setState({ persons: [ ...this.state.persons, ...data ]})

Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax