【发布时间】:2019-05-21 14:31:56
【问题描述】:
- 当改变一个组件的状态然后改变 url 时,preact 组件没有卸载
- 问题是 IE 和 safari 特有的
- 使用浏览器的“返回”功能时,componentDidMount 不触发,state 未设置为初始值
这是一个例子,你可以在本地运行以获得更好的理解。
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/preact/8.4.2/preact.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const React = preact;
class Foo extends React.Component {
state = {
loading: false
}
componentDidMount() {
console.log('mounted');
}
leave() {
this.setState({
loading: true
});
setTimeout(() => {
window.location.href = 'https://github.com/';
}, 2000);
}
render() {
return this.state.loading ? <div>loading...</div> : <button onClick={this.leave.bind(this)}>leave</button>;
}
}
React.render(
<Foo />,
document.getElementById('app')
);
</script>
</body>
</html>
- 点击按钮
- 等待重定向
- 返回
- 页面仍然显示:“正在加载...”
返回时重置状态的最佳解决方案是什么?
【问题讨论】:
-
我会说使用
componentWillUnmount并重置状态。但在页面导航上,它似乎没有触发该生命周期方法。 -
这就是问题所在