Uncaught Error: Hooks can only be called inside the body of a function component within Class component

Uncaught Error: Hooks can only be called inside the body of a function component within Class component

当 运行 附在底部的示例时,我收到以下错误:

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>

class 组件不支持挂钩,如果您仍然依赖某些 class 组件功能,则应将其设为功能组件或根本不使用挂钩。

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>

您也可以使用 like:

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>
  )
}