【问题标题】:Is it possible to declare constant variables outside a class component in react native?是否可以在反应原生的类组件之外声明常量变量?
【发布时间】:2021-03-19 13:54:04
【问题描述】:

我正在尝试在我的类组件之外在 react native 中创建以下常量变量:

import { Component, useState } from 'react';

const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
    

class NotificationScreen extends Component {

但是运行app时会弹出如下错误:

Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might... 

有没有办法在类中使用常量变量?

【问题讨论】:

  • 你违反了钩子的规则。 React 钩子仅在功能组件或其他自定义反应钩子中有效。 React 钩子与 const 变量声明无关,这些是标准的 javascript。它们几乎可以在任何地方声明。您要解决的问题是什么?

标签: reactjs react-native class react-hooks constants


【解决方案1】:

您正在使用 Hooks 类内组件定义 state,这就是您遇到错误的原因。您可以仅在功能组件中使用 Hooks,并且只能在其中使用 Hook,但不能在其范围之外作为常量使用。

您当然可以在类之外定义常量并且可以使用它,但它只能是static 数据,例如 HTTP 请求的BaseURL 或用户类型等,但如果您必须使用state,则需要在类中定义它。

你可以使用Hookslike来实现它

import { Component, useState } from 'react';

function NotificationScreen(props) {

  const [isEnabled, setIsEnabled] = useState(false); 
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

}

如果你想使用类,那么你可以像这样实现它

import { Component, useState } from 'react';

class NotificationScreen extends Component {

  state = { isEnabled : false } 

  toggleSwitch = () => {
    this.setState({ isEnabled: !this.state.isEnabled }); 
  }    
}

【讨论】:

  • 我知道这解决了钩子使用中的明显错误,但它是否回答了 OP 的问题“有没有办法在类中使用常量变量?”
  • @DrewReese 我已经尝试回答并更新了它
【解决方案2】:

在基于类的组件中,您可以直接将状态用作this.state 而不是useStateuseState 用于功能组件。

所以,在你的情况下,

class NotificationScreen extends Component {
  state = {
    isEnabled: false
  }

  toggleSwitch = ()=>{
    this.setState(prevState => ({isEnabled: !prevState.isEnabled}))
  }

  render(){
    return (
      <button onPress={this.toggleSwitch}>Press Me!</button>
    )
  }

或者如果你想要一个全局状态,你将不得不使用类似redux

【讨论】:

  • 谢谢。如果有效,请单击接受刻度线。也考虑投票:)
猜你喜欢
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 2019-01-06
  • 2018-02-20
  • 1970-01-01
相关资源
最近更新 更多