React Hook“useState”无法在类组件中调用。

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


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>

                        


                    )



哈士奇WWW
浏览 116回答 5
5回答

吃鸡游戏

状态钩子 (useState) 可用于功能性 React 组件,但在您的情况下,您使用的是类组件。函数式 React 组件通常没有开箱即用的状态,但这useState是一个新功能,可以让您解决这个问题您可以将其更改为功能组件,也可以将其保留为类组件并以不同的方式使用状态,例如:!this.state.open而不是!open&nbsp;和this.setState({open: false})代替setOpen(false)https://reactjs.org/docs/hooks-state.html

喵喵时光机

将此行更改const [open, setOpen] = useState(false);为this.state = { open: false };当设置为 true 时,只需调用&nbsp;this.setState({ open: this.state.open: true })

红糖糍粑

您必须使用功能组件。目前你的组件是一个类组件,所以你应该有类似的东西:const Navbar = (props) => {&nbsp; const { authenticated } = props;&nbsp; const [open, setOpen] = useState(false);&nbsp; const handleDrawer = () =>{&nbsp; &nbsp; setOpen(true)&nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; return (&nbsp; &nbsp; <AppBar position="fixed">...</AppBar>&nbsp; );};我还注意到您的类组件具有在渲染方法中定义的状态部分。使用类组件时,应该在constructor中定义状态,否则每次渲染时您的状态都会被覆盖。

幕布斯7119047

使用function Navbar(props)代替class Navbar extends Component这是因为,有一个规则:React Hook“useState”不能在class componenteg中调用class Navbar extends Component。React function componentReact Hooks 必须在例如function Navbar(props)或自定义 React Hook 函数中调用

富国沪深

函数组件而不是类组件怎么样?如您所知,推荐使用功能组件。我认为它很容易编码并且可以提高性能。const Navbar = () => {&nbsp; &nbsp; &nbsp;//useState, define functions here&nbsp; &nbsp; &nbsp;return (//the same as render method of your class component)&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript