【问题标题】:React Native hooks - correct use of useEffect()?React Native 钩子 - 正确使用 useEffect()?
【发布时间】:2020-09-15 19:50:47
【问题描述】:

我是 hooks 的新手,在 SO 上遇到了这个设置,想确认这是正确的模式。我之前收到了 RN“未安装的组件”泄漏警告消息,这似乎解决了它。我试图以某种方式模仿compnentDidMount。这是电话号码验证注册流程和 onMount 的一部分,我只想检查 navigation,然后触发副作用,设置挂载 true,然后正确卸载。

const SMSVerifyEnterPinScreen = ({ route, navigation }) => {

  const [didMount, setDidMount] = useState(false)
  const { phoneNumber } = route.params

  useEffect(() => {
    if(navigation) {
      signInWithPhoneNumber(phoneNumber)
      setDidMount(true)
    }
    return () => setDidMount(false)
  }, [])

  if (!didMount) { return null }

  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
    ...
  }

  return (
    ...
  )
}

带有 react-nav 5 的 RN 0.62.2 - 谢谢!

【问题讨论】:

  • didMount 的目的是什么。它似乎没有完成任何事情。你在signInWithPhoneNumber中设置一些状态吗?
  • 是在signInWithPhoneNumber中设置多个状态

标签: react-native react-hooks react-functional-component


【解决方案1】:

由于 signInWithPhoneNumber 是一个异步函数,并且会设置状态,因此您会看到警告它组件在响应可用之前已卸载

为了处理这种情况,您可以保留一个变量来跟踪它是否已安装,然后只有设置状态是已安装的变量为真

但是,如果组件已卸载,则不需要返回 null,因为这不会完成任何操作。该组件已从视图中移除,并且无论如何都不会呈现任何内容。

另外你不需要在 state 中维护这个值,而是使用一个 ref

const SMSVerifyEnterPinScreen = ({ route, navigation }) => {

  const isMounted = useRef(true)
  const { phoneNumber } = route.params

  useEffect(() => {
    if(navigation) {
      signInWithPhoneNumber(phoneNumber)
    }
    return () => {isMounted.current = false;}
  }, [])


  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
    ...
  }

  return (
    ...
  )
}

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多