gpt4 book ai didi

ReactJS componentWillUnmount 未在路由更改时调用

转载 作者:行者123 更新时间:2023-12-04 02:09:22 29 4
gpt4 key购买 nike

我正在使用出色的 create-react-app 工具来构建应用程序。我的问题正如标题所暗示的那样微不足道,但我无法解决。我已经在 github 上发布了一个简单的应用程序来说明:

https://github.com/diarmuidoconnor/reactdemo

相关节选如下。

路由配置是:

     <Router history={browserHistory} >
<Route path="/" component={App}>
<IndexRoute component={Foo}/>
<Route path="bar" component={Bar} />
</Route>
</Router>

Bar组件代码为:

 var Bar = React.createClass({
componentWillUnmount: function() {
localStorage.setItem('view', 2) ;
},
componentWillMount: function() {
console.log('mounting') ;
localStorage.setItem('view', 1) ;

},

render: function(){
return (
<div>
<h1>Bar </h1>
</div>
);
}
});

如您所见,它具有 componentWillMount 和 componentWillUnmount 生命周期方法。前者在我导航到/bar 时被调用(localStorage 具有正确的值 1,用于 View 键)但后者在我移动到不同的 URL (/) 时不会被调用 - View 键的 localStorage 值没有更改为 2 ,如我所料。它仍然是 1。

我的环境

  • 操作系统 10.9
  • 节点 v4.2.2
  • npm 2.14.7
  • Chrome 版本 53.0.2785.143

最佳答案

我猜您正在手动更改 url 以在路线之间导航。通过这样做,您将看不到想要实现的目标。您必须通过应用程序导航来完成。

添加带有这两个链接(App 和 Bar)的标题并使用 React 的“链接”进行导航。

但这里我只是在栏页中添加一个指向主页的链接。

import React from 'react';
import { IndexLink } from 'react-router';

var Bar = React.createClass({
componentWillUnmount: function() {
console.log('unmounting') ;
localStorage.setItem('view', 2) ;
},
componentWillMount: function() {
console.log('mounting') ;
localStorage.setItem('view', 1) ;
},
render: function(){
return (
<div>
<h1>Bar </h1>
<IndexLink to="/" activeClassName="active">Home</IndexLink>
</div>
);
}
});

export default Bar;

这足以检查“componentWillUnmout”功能。

关于ReactJS componentWillUnmount 未在路由更改时调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40147503/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com