调用 Axios 成功后如何更新页面?react

IT技术 reactjs
2022-07-21 01:21:31

所以我正在做一个使用Axioswith的项目Json-server,但是我有一个问题,每次我做 aPatch时,我都必须在主页上给 F5 以更新它,我想知道我该怎么做才能让它不会发生,并自动。

我的Patch

  onSubmitDate = event => {
    const newUrl = prompt("Please with new URL:");
    const personCurrent = event.target.value;
    axios.patch(`http://localhost:3004/employee/${personCurrent}`, {
    url_git: newUrl
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
}

我的Get

  componentDidMount() {
    axios
      .get("http://127.0.0.1:3004/employee")
      .then(response => this.setState({ employee: response.data }));
  }

有人可以帮助我吗?

1个回答

我假设更新在您正在处理的组件上。

要创建组件的重新渲染,您可以简单地设置状态。在这里查看更多 您的回复格式是什么?它是否包含您希望显示的更新数据?如果是这种情况,这很容易,只需setState在您的then:

  onSubmitDate = event => {
    const newUrl = prompt("Please with new URL:");
    const personCurrent = event.target.value;
    axios.patch(`http://localhost:3004/employee/${personCurrent}`, {
    url_git: newUrl
  })
  .then(response => {
    console.log(response);
    this.setState({employee: response.data})
  })
  .catch(error => {
    console.log(error);
  });
}

如果响应没有提供您想要在组件中更新的数据,您可以简单地获取您想要在thenPATCH 中的任何数据并设置其响应的状态。所以是这样的:

  onSubmitDate = event => {
    const newUrl = prompt("Please with new URL:");
    const personCurrent = event.target.value;
    axios.patch(`http://localhost:3004/employee/${personCurrent}`, {
    url_git: newUrl
  })
  .then(response => {
    console.log(response);        
    axios.get("http://127.0.0.1:3004/employee")
      .then(response => this.setState({ employee: response.data }));

  })
  .catch(error => {
    console.log(error);
  });
}