React Native-无效的挂钩调用。挂钩只能在功能组件的主体内部调用

时间:2020-01-14 13:23:07

标签: react-native mobile

这是屏幕截图中的代码实现。我刚刚创建了一个简单的应用程序,其中包含一个按钮和一个输入字段,在其中保存输入文本并在按下按钮后在登录控制台中进行打印,但是显示为**const [enterGoal, setGoalState] = useState('')**错误。有人可以看看吗?

code implementation screenshot Error screenshot

2 个答案:

答案 0 :(得分:0)

问题是您正在使用类组件,而挂钩应在功能组件中使用。所以多数民众赞成在错误。如果您使用的是类,请尝试使用setState方法来更新状态,并在构造函数中定义状态。像

constructor(props){
this.state={
nameOfPerson:'robert'
}
}

在任何函数中都执行this.setState({nameOfPerson:'wowo'})进行更改,

答案 1 :(得分:0)

您在类组件中使用钩子。钩子在功能组件中起作用

例如

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

更多支票documentation