React axios DELETE和POST添加到数据库但不更新状态

时间:2018-04-07 16:02:37

标签: reactjs axios

当我删除某个项目时,它会从数据库中删除,但在刷新页面之前状态不会更新。

我的理解是我不想直接更新状态,我想制作状态的副本,修改它,然后覆盖现有的状态,这应该触发一个新的渲染,因为它也会从数据库。

所以我认为传播操作符对此非常理想,但我似乎无法重新渲染它。

  class Projects extends Component {
  state = {
    projects: []
  };

  getProjects() {
    axios
      .get('http://localhost:5309/api/projects')
      .then(response => {
        this.setState({ projects: response.data });
      })
      .catch(error => console.log(error));
  }

  deleteProject(event) {
    axios
      .delete(`http://localhost:5309/api/projects/${event.target.value}`)
      .then(response => {
        this.setState({ projects: response.data });
      })
      .catch(error => {
        console.log(error);
      });
  }

  componentDidMount() {
    this.getProjects();
  }

  render() {
    return (
      <div className="Projects">
        <h1>Projects</h1>
        <div className="projectContainer">
          {this.state.projects.map(project => {
            return (
              <div className="projects" key={project.id}>
                <Card>
                  <CardBody>
                    <CardTitle>Name: {project.name}</CardTitle>
                    <CardText>
                      Project Description: {project.description}
                    </CardText>
                  </CardBody>
                  <Button color="secondary">Edit</Button>
                  <Button
                    color="danger"
                    type="submit"
                    value={project.id}
                    onClick={this.deleteProject}
                  >
                    Delete
                  </Button>
                </Card>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default Projects;

0 个答案:

没有答案