【问题标题】:React Hooks, useEffect unmount component issueReact Hooks,useEffect 卸载组件问题
【发布时间】:2020-02-20 22:56:57
【问题描述】:

周四好人,我有下一个代码:

  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 等使用旧的反应方式?

【问题讨论】:

    标签: reactjs react-redux react-hooks mqtt


    【解决方案1】:

    我相信您的第一个效果需要返回 unsub 函数。你不应该有两种效果。随着对这些 [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])
    

    【讨论】:

    • 是的,还是不行(我换了另一条路线再回来,我得到了双重订阅)但是你有理由,谢谢
    【解决方案2】:

    对不起朋友,这里的问题是 redux 的实现......所以我需要将 mqtt.subscriptions 和 mqtt.on('message', (...) => {}) 传递给我的 redux 操作和减速器文件。谢谢!

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2021-03-30
      • 2020-06-12
      • 2021-11-23
      • 2020-01-24
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2020-03-23
      相关资源
      最近更新 更多