反应挂钩 - 状态在功能中失去价值

react hooks - state lose value in function

我遇到了问题,我使用反应挂钩来跟踪用户令牌,并使用令牌在套接字连接中识别该用户。 问题是当我安装组件并设置套接字时令牌按预期工作,当应用程序进入后台后我关闭套接字但是当应用程序进入前台并且我执行 setToken 函数以重新设置连接时函数中的标记有他的起始值(false)。我在屏幕上打印令牌,并且当函数在屏幕上显示为 false 时也正确打印。

这是我的代码:


let socket;

const Chat = (props) => {
  const [messages, setMessages] = useState([]);
  const [users, setUsers] = useState({});
  const [token, setToken] = useState(false);

  useEffect(() => {
    init();
    return ()=> { 
      socket.close();
      AppState.removeEventListener('change', appStateChange);  
    }
  }, []);

  const init = async () => {
    // [...] get the token
  };

  const appStateChange = async (newState) => {
    if (newState === "active") {
      setSocket(); //--------- EXECUTING FROM HERE THE TOKEN IS FALSE ---------//
    }
    if (newState !== "active") {
      socket.close();
    }
  }  

  useEffect(() => {
    if (token) {
      setSocket(); //--------- EXECUTING FROM HERE THE TOKEN IS CORRECT ---------//
    }
  }, [token]);

  const setSocket = async () => {
    socket = io("http://192.168.1.172:3000/", {
        query: {
        token: token, 
        userTo: props.userTo
      },
    });

    socket.on("init", (data) => {
      setUsers(data.users);
      setMessages(data.messages);
    });

    socket.on("newMessage", (data) => {
      onReceive({
        _id: data._id,
        text: data.text,
        createdAt: new Date(),
        user: {
          _id: data.user._id,
          name: data.user.name,
          avatar: data.user.avatar,
        },
      });
    });
  };

  const onSend = useCallback((messages = []) => {
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, messages)
    );
    socket.emit("newMessage", messages);
    console.log(messages)
  }, []);

  const onReceive = useCallback((received) => {
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, received)
    );
  }, []);

  return (
    <View style={{flex:1}}>
      <Text>{token}</Text>
      {/*--------- HERE THE TOKEN IS CORRECT ---------*/}
    </View>
  );
};

export default Chat;

您错过了一些州设置!

  1. 当应用程序进入后台时,您没有清除令牌。
  2. 对于 appStateChange 函数参数 newState,您从那里初始化值
  3. 对于newState,当应用再次出现时,您没有更改值,因此不会调用setSocket()