【问题标题】:How to update the page after call Axios Successful ? React调用 Axios 成功后如何更新页面?反应
【发布时间】:2018-05-03 20:04:11
【问题描述】:

所以我正在做一个使用AxiosJson-server的项目,但是我有一个问题,每次我做Patch时,我必须在主页上给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 }));
  }

有人可以帮助我吗?

【问题讨论】:

标签: reactjs


【解决方案1】:

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

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

  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);
  });
}

如果响应没有提供您想要在组件中更新的数据,您可以简单地在 PATCH 的 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);        
    axios.get("http://127.0.0.1:3004/employee")
      .then(response => this.setState({ employee: response.data }));

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

【讨论】:

  • 是的,我也做过同样的事情:(
  • 有几件事:您是否得到了预期的响应?你是只使用一个补丁还是在 get 之后使用补丁?
  • 补丁之后是get,首先get,在我做补丁之后
  • 你能在 OP 上更新你的代码吗?将更容易查看和找出问题所在
猜你喜欢
  • 2020-12-26
  • 2020-07-18
  • 2020-07-04
  • 2020-09-28
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 2017-02-27
  • 2016-10-09
相关资源
最近更新 更多