Home > front end >  useState in class component
useState in class component

Time:01-27

can anyone tell me how to transfer it to form acceptable in class component? Thanks

const [isAuth, setIsAuth] = useState(localStorage.getItem("isAuth"));

CodePudding user response:

Something like the following

  • define the state in the constructor and initialize it with the value you use in the useState
  • create a setIsAuth method that sets the state to the new value passed

class YourComponent extends React.Component{
 
  constructor(props){
    super(props);
    this.state = {
      isAuth: localStorage.getItem("isAuth")
    }
  }

  setIsAuth = (newValue) => {
    this.setState({
      isAuth: newValue
    });
  }

  render() {
    ...
  }
}
  •  Tags:  
  • Related