React Hooks,useEffect卸载组件问题

时间:2020-02-20 22:56:57

标签: reactjs react-redux react-hooks mqtt

好星期四的人,我有下面的代码:

  const Variables = (props) => {

  const { activeVariable, mqttClient, updateRealTime } = props
  const [live] = useState(true)

  useEffect(() => {
    if (live && mqttClient) {

      // HERE I SUBSCRIBE TO TOPIC
      mqttClient.subscribe('variables_realtime')
      mqttClient.on('message', (topic, data) => {
        if (topic === 'variables_realtime') {
          const newData = JSON.parse(data.toString())
          console.log(topic, newData)
          updateRealTime(newData)
        }
      })
    }
    else mqttClient.unsubscribe('variables_realtime')

  }, [mqttClient, updateRealTime, live])

  useEffect(() => {
    return () => {
      // HERE I WANT TO UNSUBSCRIBE WHEN THE COMPONENT UNMOUNT 
      mqttClient.unsubscribe('variables_realtime')
    }
  }, [mqttClient])

  return (...)
}

所以我的问题是,当我更改为react-router-dom的其他路由时,发生了UNSUBSCRIPTION,但是当我返回到该路由时,订阅发生了两次...我不知道为什么

也许我需要对didMount,willUnmount等使用旧的react方法?

2 个答案:

答案 0 :(得分:0)

我认为您的第一个效果需要返回取消订阅功能。您不应该有两个影响afaik。随着对这些[mqttClient, updateRealTime, live]的引用发生更改,React将根据需要自动取消订阅和重新订阅。

useEffect(() => {
    if (live && mqttClient) {
      // HERE I SUBSCRIBE TO TOPIC
      mqttClient.subscribe('variables_realtime')
      mqttClient.on('message', (topic, data) => {
        if (topic === 'variables_realtime') {
          const newData = JSON.parse(data.toString())
          console.log(topic, newData)
          updateRealTime(newData)
        }
      })
    }

    return () => {
      // HERE I WANT TO UNSUBSCRIBE WHEN THE COMPONENT UNMOUNT 
      mqttClient.unsubscribe('variables_realtime')
    }

  }, [mqttClient, updateRealTime, live])

答案 1 :(得分:0)

对不起,这里的问题是redux的实现...所以我需要将mqtt.subscriptionsmqtt.on('message', (...) => {})传递到我的redux的action和reducers文件中。谢谢!