将 useState 转换为 class 组件

Converting useState to a class component

正在尝试向我现有的 React 应用程序添加登录页面。正在学习本教程 https://www.digitalocean.com/community/tutorials/how-to-add-login-authentication-to-react-applications

卡在了第 1 步,因为我们不能在 class 个组件中使用钩子。我的应用程序是一个 class 组件。

所以,我想知道如何在 class 组件中创建与此等效的内容?

  const [token, setToken] = useState();

if(!token) {
    return <Login setToken={setToken} />
  }

我已经试过了。我是反应的新手。

this.state = {
token: null
}

newToken = (e) => {
    this.setState({token: e})
  }
    
  if (!this.state.token) {
    return <Login onChange={this.newToken} />
  }

相当于您提供的代码的class组件是:

class Example extends React.Component {
  state = {
    token: undefined, // Not strictly necessary, as it will be undefined even if you leave this line out
  }

  render() {
    const { token } = this.state;
    if (!token) {
      return <Login setToken={(newToken) => this.setState({ token: newToken })} />
    }
  }
}