简体   繁体   中英

How to React re-render list view from database ondelete

I have 2 files here one is the parent component sending data from the database, the other is the rendered info with a delete button.

Here is my latest attempt to delete the data from the data base (works) and re-render the list (doesn't re-render) current error is that email is not a valid variable.

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

class Admin extends Component {

  constructor(props) {
    super(props);
    this.state = {
    allEmails: []
  }
  this.hideEmail = this.hideEmail.bind(this, email)
}

  componentDidMount() {
    fetch("/api/emails/")
      .then(res => res.json())
      .then(parsedJSON => parsedJSON.map(emails => ({
        email: `${emails.email}`,
        id: `${emails.id}`
      }))).then(emails => this.setState({allEmails: emails}))
  }

  hideEmail = () => this.setState({allEmails:emails})

  render() {
    return (
      <div>
        <h2>Admin Page</h2>
        <div>
          {this.state.allEmails.map((email) => {
            return <EmailItem
              key={email.id}
              email={email.email}
              onDelete = {() => this.onDelete(this, email.email)}/>
          })}
        </div>
      </div>
    );
  }
}

export default Admin;



import axios from 'axios'
import React, { Component } from 'react';



const EmailItem = ({email, onDelete}) => (

  <div>
    <h3>{email}</h3>
    <button
      onClick={(e) => {
      e.preventDefault()
      axios.delete("/api/emails/delete/", {
        data: {email: email}
      })
      onDelete()
      }
    }
    >
      Remove
  </button>
  </div>
)
export default (EmailItem)

It looks like your Admin component doesn't know of the changes that happened on the backend. You fire off a delete, which works, but that component only gets the "allEmails" on mount. With the component already mounted, you aren't calling the fetch again to get the latest email list, so it never re-renders.

There are a few ways to handle this, but basically you'll want to fetch the new list after the axios delete completes successfully.

An option would be to create a new function in your Admin component that will fetch the email list. You can then call that in the componentDidMount function and then also pass it to the child EmailItem component, which it can call when the delete call has been successful.

You are passing an onDelete() function, to that component, but I don't see that defined in your code. If that's the intention of that function, make sure it's refetching the latest list of emails and setting state to force the refresh.

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