【问题标题】:Add and remove data to table - React向表中添加和删除数据 - React
【发布时间】:2019-01-25 21:31:34
【问题描述】:

我正在制作一个简单的姓名和电子邮件列表 - 在 React 中按表格。我想从服务器获取数据,然后可以动态添加或删除人员。这是我使用 React 的第一步,所以我遇到了问题。

import React, { Component } from 'react';
import Form from "./Form";

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

        this.state = {
            people: [],
        };

        this.addPerson = this.addPerson.bind(this);
    }

    addPerson(name, email) {
        this.state.people.push({name: name, email: email});
    }

    componentDidMount() {
        this.getPeople();
    }

    getPeople() {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(response => this.setState({people: response}))
            .catch(error => console.log(error));
    }


    render() {
        return (
            <div className='App'>
                <Form/>
                <table>
                    <thead>
                    <tr>
                        <th>LP</th>
                        <th>USER</th>
                        <th>EMAIL</th>
                    </tr>
                    </thead>
                    <tbody>
                    {this.state.people.map((person, index) => {
                        return (
                            <tr key={person.email}>
                                <th>{index + 1}</th>
                                <td>{person.name}</td>
                                <td>{person.email}</td>
                            </tr>
                        )

                    })}
                    </tbody>
                </table>
            </div>
        )
    }

}

export default App;

和表单组件:

import React, { Component } from 'react';

class Form extends Component {
    constructor() {
        super();

        this.state = {
            name: this.props.name,
            email: this.props.email
        };

        this.handleChange = this.handleChange.bind(this);
        this.addPerson = this.addPerson.bind(this);

    /*    this.formSubmit = this.formSubmit.bind(this); */
    }

    handleChange(e) {
        this.setState({[e.target.id]: e.target.value})
    }

    addPerson(name, email) {
        this.props.addPerson(name, email);
        this.setState({name: '', email: ''});
    }

    render() {
        return (
            <form>
                <input id='name' type='text' name={this.state.name} placeholder='Name...'/>
                <input id='email' type='text' email={this.state.email} placeholder='Email...'/>
                <input onClick={() => this.addPerson(this.state.name, this.state.email)} type='submit' value='submit'/>
            </form>
        )
    }

}

export default Form;

现在我想可以将数据添加到表格以提交表格,或者如果我愿意,可以删除表格的数据。我被困在这一刻......

【问题讨论】:

  • 什么不起作用?
  • TypeError: 无法读取未定义的属性“名称”,表单组件,第 8 行。暂时。

标签: javascript reactjs forms


【解决方案1】:

我会重写你的代码如下。

我会将Form 组件设为uncontrolled component。这意味着,当您更改时,表单输入将保持其自己的内部状态。无需维护两个不同的数据源。所以我会依赖父组件App状态。我还添加了一个表单提交处理程序,它将在提交时获取输入值,然后从App 调用addPerson 方法将名称添加到由根组件App 维护的people 状态。

我添加了deletePerson 方法来从列表中删除人员。这是 2 个组件的样子。

这里的

deletePerson 方法依赖于人员列表将包含具有 uniq 电子邮件的人员这一事实。因为您也选择它作为key 道具。但是,如果您了解当前的代码流程,您可以随时更改此标准。

App.js

import React, { Component } from "react";
import Form from "./Form";

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

    this.state = {
      people: []
    };

    this.addPerson = this.addPerson.bind(this);
    this.deletePerson = this.deletePerson.bind(this);
  }

  addPerson(name, email) {
    this.setState(prevState => ({
      people: [...prevState.people, { name, email }]
    }));
  }

  componentDidMount() {
    this.getPeople();
  }

  getPeople() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(response => this.setState({ people: response }))
      .catch(error => console.log(error));
  }

  deletePerson(email) {
    return () => {
      this.setState(prevState => ({
        people: prevState.people.filter(person => person.email !== email)
      }));
    };
  }

  render() {
    console.log(this.state);

    return (
      <div className="App">
        <Form addPerson={this.addPerson} />
        <table>
          <thead>
            <tr>
              <th>LP</th>
              <th>USER</th>
              <th>EMAIL</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {this.state.people.map((person, index) => {
              return (
                <tr key={person.email}>
                  <th>{index + 1}</th>
                  <td>{person.name}</td>
                  <td>{person.email}</td>
                  <td>
                    <button onClick={this.deletePerson(person.email)}>
                      Delete
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

Form.js

import React, { Component } from "react";

class Form extends Component {
  constructor() {
    super();
    this.formSubmit = this.formSubmit.bind(this);
  }

  formSubmit(event) {
    event.preventDefault();
    const form = event.target;
    const email = form.elements["email"].value;
    const name = form.elements["name"].value;
    this.props.addPerson(name, email);
    form.reset();
  }

  render() {
    return (
      <form onSubmit={this.formSubmit}>
        <input
          id="name"
          type="text"
          defaultValue=""
          placeholder="Name..."
        />
        <input
          id="email"
          type="text"
          defaultValue=""
          placeholder="Email..."
        />
        <input type="submit" value="submit" />
      </form>
    );
  }
}

export default Form;

请查看Codesandbox演示。

【讨论】:

  • 非常感谢!
【解决方案2】:

您必须为您的 App 组件创建一个 deletePerson 函数,然后将 deletePerson 和 addPerson 作为 props 传递给您的 Form 组件,如下所示:

<Form addPerson={this.addPerson} deletePerson={this.deletePerson} />

然后在您的表单组件中使用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2021-11-21
    相关资源
    最近更新 更多