reactjs - reactjs中的条件componentWillUnmount()
问题描述
单击时button
,quote
应该使用卸载,componentwillunmount()
但我通过登录到控制台进行了检查,卸载根本没有运行。
import React from "react";
import "./App.css";
class App extends React.Component {
constructor() {
super();
this.state = {
quote: ""
};
}
handleAction = () => {
this._isRemoved = true;
console.log("Clicked");
};
componentDidMount() {
this._isRemoved = false;
if (!this._isRemoved) {
this.setState({ quote: "Something" });
console.log("Mounted");
}
}
componentWillUnmount() {
this._isRemoved = true;
console.log("Unmount");
}
render() {
return (
<div className="App">
<div>
<q>{this.state.quote}</q>
<br />
<button onClick={this.handleAction}>Click Here</button>
</div>
</div>
);
}
}
export default App;
解决方案
当您更改页面或整个组件将消失的东西时调用它的卸载。
你可以像这个例子一样简单地隐藏或显示你的元素:
import React from "react";
import "./App.css";
class App extends React.Component {
constructor() {
super();
this.state = {
quote: "",
_isRemoved :false
};
}
handleAction = () => {
this.setState({
_isRemoved : true
})
console.log("Clicked");
};
showAction = () => {
this.setState({
_isRemoved : false
})
console.log("Clicked");
};
componentDidMount() {
this.setState({ quote: "Something" });
console.log("Mounted");
}
componentWillUnmount() {
this._isRemoved = true;
console.log("Unmount");
}
render() {
return (
<div className="App">
<div>
{!this.state._isRemoved &&
<q>{this.state.quote}</q>
}
<br />
<button onClick={this.handleAction}>Hide</button>
<button onClick={this.showAction}>Show</button>
</div>
</div>
);
}
}
export default App;
推荐阅读
- excel - 高级过滤器不等于 ID 列表
- flutter - 在 ListView.builder 的末尾添加一个元素以在 Flutter 中移回顶部?
- html - Outlook 锚标记下划线不起作用
- matlab - MATLAB App Designer 暂停/关闭抛出警告
- jquery - 如何使用jQuery datapicker根据条件从开始日期获取结束日期和休假天数
- c++ - MinGW cc1plus.exe 和 collect2.exe“无法正确启动应用程序(0xc0210000)。点击确定关闭应用程序”
- react-native - 在反应原生中按下通知时如何导航到特定屏幕
- flutter - 颤振新项目致命退出,错误代码为1
- rust - tokio::time::sleep 方法是否将任务从运行队列中取出?
- r - 如何避免在情节中重复图例并在 R 中垂直设置标题?