【问题标题】:How to use a dynamic variable in useEffect which works once when the page is loaded?如何在 useEffect 中使用动态变量,该变量在页面加载时工作一次?
【发布时间】:2022-09-30 19:45:30
【问题描述】:

我在 reactjs 上使用 socket.io。没有任何问题。一切都按预期工作。

我这样使用它:

const [username,setUsername]=useState<string>(\'\')
useEffect(() => {
        server.on(\"CORRECT_USERNAME_TO_LOGIN\",(socketId: string) => {
          dispatch(authActions.setUsername(username))
          navigate(ROUTER_PATHS.activeUsers)
        })
}, [])

如果服务器发出到CORRECT_USERNAME_TO_LOGIN通道,这种代码结构运行良好。但是有一个状态。用户名变量是一个动态值,当服务器发送到通道时我必须使用它。但是用户名变量不是当前值,它是服务器发出时的初始值。这是因为我在 useEffect 中使用它吗?

    标签: javascript node.js reactjs socket.io


    【解决方案1】:

    问题在于CORRECT_USERNAME_TO_LOGIN 侦听器函数的范围。你可以通过使用 useRef 来解决这个问题,这将在 React 的状态之外。 例子: 我假设您通过 API 调用获取用户名。

    // declare userNameRef
    const userNameRef = useRef();
    
    ...
    // this is a callback function from an API
    (data) => {
       // we are assuming that data has the username
       userNameRef.current = data;
    }
    
    ...
    // inside the useEffect use it like the following
    
    useEffect(() => {
            server.on("CORRECT_USERNAME_TO_LOGIN",(socketId: string) => {
              dispatch(authActions.setUsername(userNameRef.current))
              navigate(ROUTER_PATHS.activeUsers)
            })
    }, [])
    
    

    【讨论】:

      【解决方案2】:

      获取对您的状态变量的引用,以便您始终可以使用引用访问它的当前值:

      import { useState, useEffect, useRef } from 'react'
      
      // ...
      
      const [username, setUsername] = useState<string>('')
      const usernameRef = useRef(username)
      
      // ...
      
      useEffect(() => {
          server.on("CORRECT_USERNAME_TO_LOGIN",(socketId: string) => {
            dispatch(authActions.setUsername(usernameRef.current))
            navigate(ROUTER_PATHS.activeUsers)
          })
      }, [])
      

      您可以更新usernameRef,例如:

      usernameRef.current = 'new-username'
      

      您当前正在更新的任何位置

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-02
        • 1970-01-01
        • 2023-04-04
        • 2021-11-07
        • 2011-09-03
        • 2023-01-28
        • 2011-05-22
        • 2019-11-07
        相关资源
        最近更新 更多