You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React的AppHeader组件判断token cookie时始终进入第一个if分支如何解决?

问题根因

代码的判断逻辑存在逻辑运算符使用错误:
当前判断条件为cookies.get('token') !== undefined || cookies.get('token') !== '',使用的是逻辑或(||),规则为只要任意一个子条件成立,整个表达式结果就为真:

  • 当token为undefined时,cookies.get('token') !== '' 条件成立(undefined不等于空字符串),整个表达式结果为真
  • 当token为''空字符串时,cookies.get('token') !== undefined 条件成立(空字符串不等于undefined),整个表达式结果也为真

也就是说无论token是undefined还是空字符串,if条件永远成立,所以始终会进入第一个分支返回登出按钮。

修复方案

方案1:替换逻辑或为逻辑与(&&)

调整判断规则为「token既不是undefined也不是空字符串」时才判定为登录有效,进入第一个分支:

class AppHeader extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        // 将逻辑或||替换为逻辑与&&
        if (cookies.get('token') !== undefined && cookies.get('token') !== '') {
            return (<div className={styles.container}>
                <button onClick={this.stravante}>[ Logout ]</button>
            </div>)
        } else {
            return (<div></div>)
        }
    }
}

方案2:简化隐式布尔判断

undefined、空字符串在JS中都属于假值,可以直接简化判断逻辑,同时提前取值避免重复调用cookies.get方法:

class AppHeader extends React.Component {
    constructor(props) {
        super(props)
    }
    render() {
        const token = cookies.get('token')
        // 直接判断token是否为真值即可
        if (token) {
            return (<div className={styles.container}>
                <button onClick={this.stravante}>[ Logout ]</button>
            </div>)
        } else {
            return (<div></div>)
        }
    }
}

这种写法更简洁易读,也能降低逻辑运算符写错的概率。

内容的提问来源于stack exchange,提问作者Captain Shane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 01:06:02