首页 > 解决方案 > 没有未使用的变量

问题描述

在我的 useState 钩子中,我正在导入上下文;因此, setUser 将被闲置并给我和 Eslinting 警告。我不确定如何扼杀这个警告,并且已经没有办法做到这一点。如果有人在 React 中有一个建议或最佳实践来扼杀这个警告,我将不胜感激。代码如下:

import React, { useContext } from 'react'
import { Link } from 'react-router-dom'
// Material UI
import Button from '@material-ui/core/Button'
import Grid from '@material-ui/core/Grid'
import Container from '@material-ui/core/Container'
import User from './User'
// context
import { ProfileContext } from '../contexts/ProfileContext'
const Header = ({ isAuth, logout }) => {
  const [user, setUser] = useContext(ProfileContext)
  return (
    <Container maxWidth="lg" style={{ padding: 10 }}>
      <Grid container justify="space-between">
        <Grid item xs={2}>
          <Button color="inherit" component={Link} to="/">
            Jobtracker
          </Button>
        </Grid>
        <Grid item xs={10} container justify="flex-end">
          <div>
            {isAuth ? (
              <>
                {user && user.user.admin && (
                  <Button color="inherit" component={Link} to="/admin">
                    Admin
                  </Button>
                )}
                <Button color="inherit" component={Link} to="/profile">
                  Profile
                </Button>
                <Button color="inherit" component={Link} to="/dashboard">
                  Dashboard
                </Button>
                <Button color="inherit" onClick={logout}>
                  Logout
                </Button>
              </>
            ) : (
              <>
                <Button color="inherit" component={Link} to="/login">
                  Login
                </Button>
                <Button color="inherit" component={Link} to="/signup">
                  SignUp
                </Button>
              </>
            )}
          </div>
        </Grid>
      </Grid>
    </Container>
  )
}
export default Header

标签: javascriptreactjsreact-hooks

解决方案


当你不需要它时,你不必解构它:

const [user] = useContext(ProfileContext)

此外,如果您只需要setUser,您可以在解构时使用comma不带变量或常量名称的 a 跳过项目:

const [, setUser] = useContext(ProfileContext)

推荐阅读