为什么prop的值没有在componentWillUnmount等方法中设置?

时间:2017-07-21 13:35:47

标签: javascript reactjs

我有一个组件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。

1 个答案:

答案 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
}