【问题标题】:Typescript: variable is assigned a value but never used, except it is used打字稿:变量被赋值但从未使用过,除非它被使用
【发布时间】:2022-01-09 05:58:10
【问题描述】:

我收到 Typescript 警告:'isAuthenticated' is assigned a value but never used 用于以下组件

但是,我在我的组件中使用isAuthenticated,如下所示。

import { useAuth0 } from '@auth0/auth0-react'

const Profile: React.FC = () => {
    const { user, isAuthenticated, isLoading } = useAuth0()

    if (isLoading) {
        return <div>Loading ...</div>
    }

    return (
        <>
            isAuthenticated && (
            <div>
                <img src={user?.picture} alt={user?.name} />
                <h2>{user?.name}</h2>
                <p>{user?.email}</p>
            </div>
            )
        </>
    )
}

export default Profile

为什么我在使用变量时会收到此警告?

【问题讨论】:

  • 如果你渲染它,你会看到“isAuthenticated &&”作为文字输出。您想要 {isAuthenticated &amp;&amp; (... 并在末尾添加一个结束 }
  • 哦,伙计....谢谢..我是新来的反应
  • 没问题。 { 打破文字模式进入代码模式。

标签: reactjs typescript


【解决方案1】:

你用错了Logical &amp;&amp; Operator。 将() 替换为{}

更多信息:https://reactjs.org/docs/conditional-rendering.html

【讨论】:

    【解决方案2】:

    这个答案只是user2740650在上面的“评论”中分享的内容的一种实现。

    信用到期。

    import { useAuth0 } from '@auth0/auth0-react'
    
    const Profile: React.FC = () => {
        const { user, isAuthenticated, isLoading } = useAuth0()
    
        if (isLoading) {
            return <div>Loading ...</div>
        }
    
        return (
            <React.fragment>
                {isAuthenticated && (
                    <div>
                        <img src={user?.picture} alt={user?.name} />
                        <h2>{user?.name}</h2>
                        <p>{user?.email}</p>
                    </div>
                )}
            </React.fragment>
        )
    }
    
    export default Profile
    

    我希望以上答案可能对未来的一些 jsN00b 有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2020-07-06
      相关资源
      最近更新 更多