我正在使用出色的create-react-app工具来构建应用程序。我的问题与标题所暗示的一样微不足道,但我无法修复它。我已经发表在GitHub上一个最基本的应用来说明:有ReactJS componentWillUnmount不会调用路由更改
https://github.com/diarmuidoconnor/reactdemo
从它的相关摘录如下。
路由配置是:
<Router history={browserHistory} >
<Route path="/" component={App}>
<IndexRoute component={Foo}/>
<Route path="bar" component={Bar} />
</Route>
</Router>
酒吧组件代码:
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表示视图键),但后者不是当我移动到不同的URL时(/) - 视图键的localStorage值未更改为2 ,正如我所料。它仍然是在1
我的环境
- OSX 10.9
- 节点v4.2.2
- NPM 2.14.7
- 的Chrome版本53.0.2785.143
请看看[问]。在[所以]我们不写明显的东西,因为他们不需要。我们知道你会感谢任何指导,并感谢你。它是还原剂。 – xenteros
感谢Venugopal,你的回答是正确的。然而,它们在React的设计中略有不一致,因为在手动导航到URL时,新安装的组件的componentWillMount被调用**,但未调用的组件的componentWillUnmount未被调用。 – Diarmuid
@Diarmuid就是这一点。你可以接受答案,如果它解决了你的问题 – Venugopal