【问题标题】:How to redirect to another page when the current page is refreshed Reactjs刷新当前页面时如何重定向到另一个页面Reactjs
【发布时间】:2020-06-15 13:53:18
【问题描述】:

我想在当前页面重新加载或刷新时重定向到上一页,

constructor(props) {
    super(props);
    this.onUnload = this.onUnload.bind(this);
    this.onbeforeunload= this.onbeforeunload.bind(this)
    this.state = {
      show_answers: [],
      other_data: [],
      question: "",
      answer: "",
      id: 0,
    };
  }



onUnload() {
    console.log("reloads")
this.context.router.push('/getanswer');
}

onbeforeunload(){
  console.log("reloadsssss")
this.context.router.push('/getanswer');
}

我已经尝试了上述方法,但没有提出任何建议。

【问题讨论】:

  • 刷新是指浏览器的F5吗?
  • 是的,如果用户重新加载它
  • @NabeelAyub 嗯,它对工具有影响
  • 那么我该如何管理呢?
  • @NabeelAyub 在重定向时传递一个 state 属性,并在特定页面上将其设置为 null。您可以在此特定组件中检查它

标签: reactjs react-router react-router-dom


【解决方案1】:

ReactJs 没有任何方法来监听重载事件。使用这个普通的 Javascript 事件处理程序:

window.onbeforeunload = (e) => {
  this.context.router.push('/getanswer');
};

美国也可以把这个(在构造函数上):

constructor(props) {
  if (window.performance) {
    if (window.performance.navigation.type == 1) {
      //This page is reloaded
      this.context.router.push('/getanswer');
    }
  }
}

【讨论】:

    【解决方案2】:
    componentDidUpdate() {
      this.context.router.push('/getanswer');
    }    
    

    每当页面加载时,componentDidUpdate 方法都会被调用并重定向到上一页。

    【讨论】:

    • 即使重定向 @Sajish 也会重新路由
    • 当用户重新加载页面时,该方法不会触发。 (来自文档 - “初始渲染不调用此方法。”)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多