从 Hooks 重构为 class 组件

Refactoring from Hooks to a class component

能否请您帮忙将一些代码从 React Hooks 重构为 class 组件?我是 React 的新手,这让我很难过。我知道 { useState } 提供了一些 "getter" 和 "setter",但不知道如何将其重构为 "typical" React class 组件中带有 props 的状态。

挂钩:

export default function App() {
const [counter, setCounter] = useState([]);
}

反应:

class App extends React.Component {
state = {
counter:
}

你可以看看这个例子。这是 increment/counting 的典型 class 组件。

class App extends React.Component {
  state = { count: 0 }

  increment = () => {
      this.setState({
         count: this.state.count + 1
      });
  }

  render(){
     return(
    <button onClick={this.increment}>+</button>
    );
  }

}

export default App;

这是它的 Hooks 实现。

 function App(){
  const [count, setCount] = useState(0);

 const increment = () => {
    setCount(count+1);
  };

  return(
    <button onClick={increment}>+</button>
   );
 }
export default App;

来自反应Hooks FAQ page

Should I use Hooks, classes, or a mix of both?
When you’re ready, we’d encourage you to start trying Hooks in new components you write. Make sure everyone on your team is on board with using them and familiar with this documentation. We don’t recommend rewriting your existing classes to Hooks unless you planned to rewrite them anyway (e.g. to fix bugs).

You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.

为了回答您的问题,等效的 class 组件将是:

class App extends React.Component {
  state = {
    counter: [] // equivalent of useState([]);
  }
  ...
  this.setState(prevState => ({
    counter: [...prevState.counter, newelement]
  })) // equivalent of setCounter(counter => [...counter, newelement]);
}