未捕获的错误:只能在Class组件内的函数组件内部调用钩子

时间:2018-11-20 05:27:53

标签: javascript reactjs react-hooks

运行底部附带的示例时,出现以下错误:

react-dom.development.js:49 Uncaught Error: Hooks can only be called inside the body of a function component.
    at invariant (react-dom.development.js:49)
    at resolveCurrentlyRenderingFiber (react-dom.development.js:11633)
    at useReducer (react-dom.development.js:11830)
    at Object.useState (react-dom.development.js:11824)
    at Object.useState (react.development.js:2574)
    at App.render (<anonymous>:25:35)
    at finishClassComponent (react-dom.development.js:14466)
    at updateClassComponent (react-dom.development.js:14429)
    at beginWork (react-dom.development.js:15233)
    at performUnitOfWork (react-dom.development.js:17940)

class App extends React.Component {
  render() {
    const [name, setName] = React.useState('Mary');
    const [age, setAge] = React.useState(10);

    return (
      <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
      </div>
    );
  }
}

ReactDOM.render(
  <div>
    <App />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

2 个答案:

答案 0 :(得分:3)

类组件中不支持钩子,如果您仍然依赖某些类组件功能,则应使其成为功能组件或根本不使用钩子。

function App() {
  const [name, setName] = React.useState('Mary');
  const [age, setAge] = React.useState(10);

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}

ReactDOM.render(
  <div>
    <App />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

答案 1 :(得分:0)

您也可以这样使用:

class App extends React.Component {
  renderApp() { // function within class component
    const [name, setName] = React.useState('Mary');
    const [age, setAge] = React.useState(10);

    return (
      <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
      </div>
    );
  }
  render() {
    return this.renderApp()
  }
}

如果您要渲染其他内容,这将进一步有用,并且对于使用其他生命周期挂钩也将有所帮助:

render() {
  return (
    <div>
     <h1>My App</h1>
     { this.renderApp() }
    </div>
  )
}