【问题标题】:ReactJs: How to Reload/refresh/re-render component without using window.location.reload()ReactJs:如何在不使用 window.location.reload() 的情况下重新加载/刷新/重新渲染组件
【发布时间】:2021-01-25 11:42:32
【问题描述】:

我想重新加载/刷新/重新渲染我的组件,但不使用 ‍‍‍window.location.reload()。有没有可能的方法来做到这一点。我已经尝试过 this.forceUpdate() 和 this.setState({ state: this.state }); 但这些对我来说实际上并没有帮助。 p>

 testDoneHandler(e) {
    if( this.state && e.origin === document.location.origin ) {
      if( e.data === 'testingClosed' ) {
        this.setState({ state: this.state });
      
      }
    }
  }



 componentDidMount() {
    window.addEventListener('message', this.testingClosed.bind(this));
  }

任何建议/帮助都会有所帮助。提前致谢

【问题讨论】:

  • 为什么要刷新组件?通常,重新渲染组件的主要原因是 prop/state 发生变化。
  • @LawynnJana 所以你有什么建议。我们可以在不实际影响更改的情况下重新渲染这个组件吗?
  • reactgo.com/react-refresh-page 根据本指南,您可以尝试this.setState({}); 刷新单个组件(我从未尝试过)
  • @GiovanniEsposito 我试过了,但没有什么对我有用。
  • @Tammy 能否展示更多代码,例如 render() 中的内容以及如何初始化 state

标签: reactjs reload


【解决方案1】:

我认为你需要这样的东西:

class t extends React.Component {
  state = {
    forceRerender: 0,
  };
  testDoneHandler(e) {
    if (this.state && e.origin === document.location.origin) {
      if (e.data === "testingClosed") {
        this.setState((value) => ({ forceRerender: value.forceRerender + 1 }));
      }
    }
  }

  componentDidMount() {
    window.addEventListener("message", this.testingClosed.bind(this));
  }

  console.log('forceUpdate', this.state.forceRerender);
}

【讨论】:

  • 您好 Taghi,感谢您抽出宝贵时间。但这不会重新渲染。有什么我错过了吗?
  • @Tammy 尝试像上面那样添加log 以使用该状态并查看状态是否正在改变
猜你喜欢
  • 2019-03-14
  • 2019-03-02
  • 2021-08-20
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
相关资源
最近更新 更多