【问题标题】:React Refresh Page反应刷新页面
【发布时间】:2020-07-27 09:23:56
【问题描述】:

我正在创建一个函数来更新我的数据库中的一些信息,并以 react 作为前端。问题是,在我更新数据库中的项目后,我希望它是实时的,但每次我进行新的更新时,我都必须再次刷新页面。 我的代码如下所示。

edit = async (id, quantity, action) => {
    if (action === "inc") {
      await this.props.updateItem(id, quantity + 1);
    }
    if (action === "dec") {
      await this.props.updateItem(id, quantity - 1);
    }
    history.push("/");
    history.push("/cart");
  };

这是我用来更新项目的功能。 请帮忙,在此先感谢。

【问题讨论】:

  • 有什么问题?在 BE 调用完成状态更新或 redux 存储更新后更新您的项目。
  • 我不想在我的代码中添加 last 到 history.push() 行。此外,我的数据仅在初始请求时来自 redux。

标签: javascript reactjs redux navigation browser-history


【解决方案1】:

查看此文档

https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class

请为 React 组件创建一个构造函数,如下所示

constructor(props) {
    super(props);
    this.state = {item: {id: 1, 'quantity': 0}; // 0 is default value.
  }

edit数量后,请将状态更新为新值

this.setState({'id': 1, quantity:  this.state.quantity + 1});

现在,使用状态来渲染 HTML

render() {
    return (<div>
        <h1>Item ID: {this.state.id}</h1>
        <h2>Item Count: {this.state.quantity}</h2>
    </div>)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2020-10-31
    • 2018-10-06
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2020-11-20
    相关资源
    最近更新 更多