【发布时间】:2023-01-04 22:54:22
【问题描述】:
我试图在反应中使用 UseState 钩子,但我不确定在哪里定义它。我试图在 React 组件中声明它,但编译器给出了错误
class VoiceCallComponent extends React.Component {
const [val, setVal] = React.useState(7);
..
..
..
}
上面的代码抛出一个错误,指出标识符需要。
【问题讨论】:
我试图在反应中使用 UseState 钩子,但我不确定在哪里定义它。我试图在 React 组件中声明它,但编译器给出了错误
class VoiceCallComponent extends React.Component {
const [val, setVal] = React.useState(7);
..
..
..
}
上面的代码抛出一个错误,指出标识符需要。
【问题讨论】:
您不能在类组件中使用 useState。您需要一个功能组件。
这是doc
这是您的示例的代码:
import React, { useState } from 'react';
function VoiceCallComponent() {
const [val, setVal] = useState(7);
// rest of the component logic goes here
return (
// JSX
)
}
【讨论】: