繁体   English   中英

React Hook“useState”无法在 class 组件中调用。 React Hooks 必须在 React function 组件或自定义 React Hook function 中调用

[英]React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

我是 React Frontend 开发的新手。 我正在尝试向我的 Material-UI NavBar 添加一个临时抽屉。 我在我的代码中添加了一个抽屉:

class Navbar extends Component {
    render() {
        const { authenticated } = this.props;
        const [open, setOpen] = useState(false);
        const handleDrawer = () =>{
           setOpen(true)
        }
        return (
            <AppBar position="fixed">
                <Toolbar className="nav-container">
                    {authenticated ? (
                        <Fragment>
                            <IconButton edge="start" onClick={handleDrawer} >
                                <Menu/>
                            </IconButton>
                            <Drawer
                                anchor='left'
                                open={open}
                                onClose={()=> setOpen(false)}
                                >
                                    <h3> Drawer</h3>
                            </Drawer>
                            <NewPost/>
                            <Link to="/">
                                <MyButton tip="Home">
                                    <HomeIcon color = "disabled"/>
                                </MyButton>
                            </Link>
                            <Link to="/chats">
                                <MyButton tip="Chats">
                                    <ChatIcon color = "disabled"/>
                                </MyButton>
                            </Link>
                            <Notifications />
                        </Fragment>
                        

                    ):(
                        <Fragment>
                            <Button color="inherit" component={Link} to="/login">Login</Button>
                            <Button color="inherit" component={Link} to="/signup">Singup</Button>
                            <Button color="inherit" component={Link} to="/">Home</Button>
                            {/* <Button color="inherit" component={Link} to="/user">Profile</Button>*/}
                        </Fragment>
                    )}
                </Toolbar>
            </AppBar>

            
        )
    }
}

Navbar.propTypes = {
    authenticated:  PropTypes.bool.isRequired
}

const mapStateToProps = state =>({
    authenticated: state.user.authenticated
})

export default connect(mapStateToProps)(Navbar)

但是出现了这个错误:

React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

所以,我创建了一个构造函数来处理这个(在渲染之前):

constructor(props) {
    super(props);
    this.state = {
      open: false
    };
  }

当我想更改 state 时,我使用了:

this.setState({ open: true })

但是,当我触发抽屉(单击按钮)时,它不会打开。 我能做什么?

state 挂钩 (useState) 可用于功能性 React 组件,但在您的情况下,您使用的是 Class 组件。 功能性 React 组件通常没有开箱即用的状态,但useState是一个新功能,可以让你解决这个问题

您可以将其更改为功能组件,或者将其保留为 class 组件并以不同方式使用 state 例如:

  • .this.state.open而不是!open
  • this.setState({open: false})而不是setOpen(false)

https://reactjs.org/docs/hooks-state.html

更改此行const [open, setOpen] = useState(false); to this.state = { open: false };

当设置为 true 时,只需调用this.setState({ open: this.state.open: true })

您必须使用功能组件。 目前你的组件是一个 class 组件,所以你应该有这样的东西:

const Navbar = (props) => {
  const { authenticated } = props;
  const [open, setOpen] = useState(false);
  const handleDrawer = () =>{
    setOpen(true)
  }
    
  return (
    <AppBar position="fixed">...</AppBar>
  );
};

我还注意到您的 class 组件在 render 方法中定义了 state 部分。 当使用 class 组件时,应该在constructor中定义 state ,否则你的 state 将在每次渲染时被覆盖。

功能组件而不是 class 组件怎么样? 如您所知,建议使用功能组件。 我认为它很容易编写代码并且可以提高性能。

const Navbar = () => {
     //useState, define functions here
     return (//the same as render method of your class component) 
}

使用function Navbar(props)代替class Navbar extends Component

这是因为,有一条规则:React Hook“useState”不能在class component中调用,例如class Navbar extends Component React Hooks 必须在React function component中调用,例如function Navbar(props)或自定义 React Hook function

暂无
暂无

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

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