javascript - 如何停止订阅商店更新?
问题描述
我将用户从组件 1 移动到组件 2 this.props.history.push
。当我在 component2 中时,看起来 component1 仍然挂载。
我尝试了所有与取消订阅商店类似的问题。
import React, {Component} from 'react';
import axios from 'axios';
import {Animate} from 'react-animate-mount';
import {translateTexts} from "../App";
import store from "../../store";
class Component1 extends Component {
constructor(props) {
super(props);
this.state = {
texts: {
computing: null
},
};
}
componentWillUnmount() {
return store.subscribe(() => {
console.log('unmount');
})
}
componentWillMount() {
store.subscribe(() => {
translateTexts(this.state.texts),store.getState().translate.userLanguage).then((res) => {{
this.setState({texts: res.data});
});
});
axios.post(`/api/`)
.then((res) => {
this.setState({show: false});
setTimeout(() => {
window.location.href = '/storage/'+res.data.id
}, 600);
})
.catch((err) => {
this.props.history.push({
pathname: '/error/'+err.response.status,
state: { code: err.response.status }});
});
});
render() {
return (
<div className="box">
Something
</div>
);
}
}
export default Component1;
import React, { Component } from 'react';
import store from "../../store";
import {translateTexts} from "../App";
class Component2 extends Component {
constructor(props) {
super(props);
this.state = {
code : null,
texts: {
msg: null
}
};
}
componentWillMount() {
this.setState( {
code: this.props.location.state.code,
});
store.subscribe(() => {
translateTexts(this.state.texts),store.getState().translate.userLanguage).then((res) => {{
this.setState({texts: res.data});
});
});
}
render() {
return (
<div>
Code: {this.state.code}
<br></br>
Message: <strong>{this.state.texts.msg}</strong>
</div>
);
}
}
export default Component2;
在componentWillUnmount
我停止订阅store
组件中的事件之后,因为现在当我store
看到我的更新登录unmount
到我的控制台时,所以Component1
以某种方式安装了。感谢您的任何建议。
解决方案
Store subscribe 应该返回unsubscribe函数,您可以在componentWillUnmount调用该函数以成功取消订阅 store。
您可以直接在componentWillMount中定义并将其存储在state中:
this.setState({
unsubscribe: store.subscribe(() => {
translateTexts(this.state.texts),store.getState().translate.userLanguage).then((res) => {{
this.setState({texts: res.data});
});
});
});
然后unsubscribe
调用componentWillUnmount
componentWillUnmount() {
this.state.unsubscribe()
}
推荐阅读
- ant - Ant 文件集仅匹配文件但不包括所有子目录
- html - 在 html 文件中打开 Angular Tree 组件
- c# - EF Core如何通过另一个列表过滤嵌套的多对多列表
- algorithm - 在有序数组中查找总和为 0 (a+b+c = 0) 的 3 个元素
- ios - UITableViewCell 内容消失
- python - Python docker SDK 内容信任不起作用
- json - 在 Vue 中为 JSON 数据创建下拉过滤器
- react-native - 如何根据 URL 中的参数从 API 中获取数据
- mysql - MYSQL 从表值中填充列
- php - Intellij IDEA - 使用 :: 和 -> 触发 PHP 代码建议,后面有空格?