我有一个组件ServerTime
,用于呈现从WebSocket连接发出的时间戳。
<ServerTime webSocket={this.props.webSocket} />
在componentDidMount
中,我使用WebSocket的EventEmitter API注册回调。
componentDidMount() {
this.props.webSocket.on('time', this.update);
}
这一切都有效。
如果我向componentWillUnmount
添加ServerTime
方法并打印出this.props.webSocket
的值,则webSocket
的值为 initial 值(false
)。
componentWillUnmount() {
console.log(this.props.webSocket); // false!
}
为什么webSocket
对象无法在componentWillUnmount
中使用?
我在这里做错了什么?
我的预感是,这是由于我对我重新选择或者immutable.js的误解。
有关信息,我使用的是redux,connect,reselect和immutable.js。
答案 0 :(得分:0)
每次商店的状态发生变异时,Immutable都会创建一个新的webSocket,你可以将webSocket保存在组件的状态中:
constructor(props) {
super(props);
const {webSocket} = props;
this.state = { webSocket };
}
并在卸载时访问webSocket:
componentWillUnmount() {
const {webSocket} = this.state;
console.log(webSocket);
// do something with webSocket
}