状态挂钩没有反应

时间:2020-07-19 15:26:15

标签: javascript reactjs react-hooks

我有以下React代码,但是我有一个问题:当按下注销按钮时,变量logged应该更新(因为令牌已从localStorage中删除),但是变量对更改没有反应因此重定向未完成。

import React, { useState, useEffect } from "react"
import { useHistory } from "react-router-dom"
import man from "../../assets/img/people/man.jpg"

const ProfileMenu = () => {
    const history = useHistory()
    const [logged, setLogged] = useState(localStorage.getItem('token') ? true : false)
    const [isOpen, setOpen] = useState(false)

    useEffect(() => {
        if (!logged) {
           handleRedirection()
        }
    })

    const handleRedirection = () => {
        history.push('/login')
    }

    const handleMenu = () => {
        setOpen(!isOpen)
    }

    const handleCloseSession = () => {
        localStorage.removeItem('token')
    }

    return (
        <div className="dropdown">
            <button 
                className="profile-menu-button"
                style={{
                    backgroundImage: `url('${man}')`
                }}
                onClick={handleMenu}
            >
            </button>
            <div 
                className="dropdown-content"
                style={{
                    display: isOpen ? 'block' : 'none'
                }}
            >
                <ul className="list">
                    <li>
                        <a>Perfil</a>
                    </li>
                    <hr/>
                    <li>
                        <a>Editar perfil</a>
                    </li>
                    <li>
                        <a>Editar red</a>
                    </li>
                    <hr/>
                    <li>
                        <a>Configuración de cuenta</a>
                    </li>
                    <li>
                        <a onClick={handleCloseSession}>Cerrar sesión</a>
                    </li>
                </ul>
            </div>
        </div>
    )
}

export default ProfileMenu

1 个答案:

答案 0 :(得分:1)

useState不会重新评估您传递给该函数的数据。您将必须自己打setLogged

 const handleCloseSession = () => {
    localStorage.removeItem('token')
    setLogged(false)
}

或者您可以使用类似以下的钩子:https://usehooks.com/useLocalStorage/