5 回答

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

TA贡献1846条经验 获得超7个赞
将此行更改const [open, setOpen] = useState(false);
为this.state = { open: false };
当设置为 true 时,只需调用 this.setState({ open: this.state.open: true })

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

TA贡献1794条经验 获得超8个赞
使用function Navbar(props)
代替class Navbar extends Component
这是因为,有一个规则:React Hook“useState”不能在class component
eg中调用class Navbar extends Component
。React function component
React Hooks 必须在例如function Navbar(props)
或自定义 React Hook 函数中调用

TA贡献1790条经验 获得超9个赞
函数组件而不是类组件怎么样?如您所知,推荐使用功能组件。我认为它很容易编码并且可以提高性能。
const Navbar = () => {
//useState, define functions here
return (//the same as render method of your class component)
}
添加回答
举报