【问题标题】:react-router: Calling componentWillUnmount across different non-nested routesreact-router:跨不同的非嵌套路由调用componentWillUnmount
【发布时间】:2017-07-21 07:00:33
【问题描述】:

我正在使用具有如下路由结构的 react-router:

const routes = (
  <Router history={browserHistory}>
    <Route path="/main" component={MainPage}></Route>
    <Route path="/charts/:chartID" component={App}></Route>
  </Router>
)

当用户从“/charts/:chartID”切换到“/main”时,我正在尝试调用流星方法。如果可能,我只希望该方法被调用一次

在 App.js 中,我使用了生命周期方法:

  componentDidUpdate(){
    Meteor.call('test',"update");   
  } // prints "update"

  componentWillUnmount(){
    Meteor.call('test',"unmount");
  } // nothing happens when url changes

Main.js(服务器):

Meteor.methods({
    'test'(obj){
        console.log(obj)
    }
})

我从source 中读到,当我的情况发生 url 变化时,组件应该卸载,但似乎我可能错过了一些东西。我应该如何解决这个问题?

非常感谢任何帮助!

【问题讨论】:

    标签: javascript reactjs meteor react-router


    【解决方案1】:

    您可以通过使用 react-redux、浏览器本地存储或其他方式以不同的方式进行操作。在react-redux,您可以更改您的商店。

    例如,您可以在商店中定义“firstTimeInCharts”并在“APP”的componentWillMount 上更新它,也可以在“MainPage”组件的componentWillMount 上设置“firstTimeInMain”并更新它。您可以通过检查这些状态来跟踪调用您的函数。您可能还想在商店中存储其他值,以便在整个应用中访问它们。

    您也可以使用浏览器的本地存储来执行相同的操作。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2017-06-07
      • 2017-11-15
      • 2015-02-21
      • 2020-06-02
      相关资源
      最近更新 更多