【发布时间】:2019-06-12 22:11:04
【问题描述】:
我通过this.props.history.push 将用户从组件1 移动到组件2。当我在 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 以某种方式挂载了。
感谢您的任何建议。
【问题讨论】:
-
一个好的做法是让您的订阅保持打开状态,直到组件卸载。您可以使用
componentWillUnmount取消订阅。您也可以订阅构造函数,但我建议您不要这样做,因为这不是构造函数的用途。
标签: javascript reactjs redux react-redux store