【问题标题】:Delete data in React using Firebase Cloud使用 Firebase Cloud 在 React 中删除数据
【发布时间】:2018-09-17 03:57:19
【问题描述】:

我是 React 新手,今天我使用 React 和 Firebase 来显示、添加和删除数据。我有一些数据获取 Firebase 并显示在卡片中。现在,我想删除一些想要的卡,但我不知道。你能告诉我怎么做吗?可能会在右上角创建“X”按钮,点击后会删除。

这是代码调用列表

const ProjectList = ({projects}) => {
  return (
    <div className="project-list section">
      { projects && projects.map(project => {
        return (
          <Link to={'/project/' + project.id} key={project.id}>
            <ProjectSummary project={project} />
          </Link>
        )
      })}  
    </div>
  )
}

这是项目摘要

const ProjectSummary = ({project}) => {
  return (
    <div className="card z-depth-0 project-summary">
      <div className="card-content grey-text text-darken-3">
        <span className="card-title ">{project.title}</span>
        <p>Created by {project.authorFirstName} {project.authorLastName} admin</p>
        <p className="grey-text">{moment(project.createdAt.toDate()).calendar()}</p>
      </div>
    </div>
  )
}

在 Firebase 中构造数据

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    您可以像这样在 ProjectSummary 列表项中添加一个删除按钮

    <button onClick={() => this.removeProject(project.id)}>Delete</button>
    

    Id 将是 firebase 唯一键,类似于 ahakhka734hfakh3

    然后在回调中我们可以调用 firebase.database() 的 remove 方法,像这样从页面中删除它。

    removeProject(projectId) {
      const projectRef= firebase.database().ref(`/projects/${projectId}`);
      projectRef.remove();
    }
    

    【讨论】:

      【解决方案2】:

      应该是这样的:

      <button onClick={() => this.removeProject(project.id)}>Delete</button>
      
         removeProject(id) {
           firebase.delete({ collection: 'project', doc:`${id}` }).then((response) => {
              console.log('delete response', response)
           }).catch((error) => {
             console.log('delete error', error)
          })
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多