简体   繁体   English

React setState 不更新 stomp.js 回调函数中的状态

[英]React setState not updating state inside stomp.js callback function

I have a page that connects to a SockJS socket over stomp.我有一个通过 stomp 连接到 SockJS 套接字的页面。 But when pass a function that is supposed to change the state to the .subscribe callback it doesn't change the page's state (the rest of the function completes normally) Here is the code:但是当将一个应该改变状态的函数传递给 .subscribe 回调时,它不会改变页面的状态(函数的其余部分正常完成)这是代码:

export default function HomePage() {

    ...some other states...

    const [isIncomingCall, setIsIncomingCall] = useState(false)

    function initSocket() {
        const socket = new SockJS(`${process.env.API_URL}/ws`);
        const stompClient = over(socket);
        stompClient.connect(
            {},
            () => onSocketConnected(stompClient),
            onSocketError
        )
        appContext.setSocket(stompClient)
    }

    function handleIncomingCall(data) {
        const state = JSON.parse(data.body.toLowerCase());
        setIsIncomingCall(state)
    }

    function onSocketConnected(stompClient) {
        const options = {
            accessToken: cookies['logged-in'],
        };

        stompClient.send("/app/connect", {}, JSON.stringify(options));
        stompClient.subscribe(`/user/search/complete`, handleSearchComplete)
        stompClient.subscribe(`/user/search/failed`, handleSearchError)
        stompClient.subscribe(`/user/call/incoming`, handleIncomingCall)
    }

    useEffect(() => {
        if (!appContext.socket && cookies['logged-in']) {
            initSocket()
        }
    }, [])

    return (
        <>
            <AnimatePresence>
                {
                    isIncomingCall && <CallModal
                        onAccept={acceptIncomingCall}
                        onReject={rejectIncomingCall}
                    />
                }
            </AnimatePresence>
            ...other page code...
        </>
    )
}

The initSocket function is called on page render inside the useEffect. initSocket 函数在 useEffect 内的页面渲染上调用。 I have tried wrapping the callback with a useCallback and binding it to the page and calling setIsIncomingCall inside an arrow function, but it didn't seem to help.我尝试使用 useCallback 包装回调并将其绑定到页面并在箭头函数内调用 setIsIncomingCall,但它似乎没有帮助。

Ok, so the problem was: Callbacks were initialized on first visiting the HomePage , but for user to set that they can receive calls, they needed to go to the ProfilePage and flip the switcher.好的,所以问题是:回调在第一次访问HomePage时被初始化,但是为了让用户设置他们可以接听电话,他们需要转到ProfilePage并翻转切换器。 In the process of going back and forth between the pages React loses the pointer to the original isIncomingCall state and sets it on the previous version of the HomePage it seems.在页面之间来回切换的过程中,React 丢失了指向原始isIncomingCall状态的指针,并将其设置在之前版本的HomePage上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM