【问题标题】:Refactoring from Hooks to a class component从 Hooks 重构为类组件
【发布时间】:2019-08-14 19:59:29
【问题描述】:

您能帮忙将一些代码从 React Hooks 重构为类组件吗?我是 React 的新手,这让我很难过。我知道 { useState } 提供了一些“getter”和“setter”,但不知道如何将其重构为具有“典型”React 类组件中的道具的状态。

钩子:

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

反应:

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

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    你可以看看这个例子。这是一个典型的递增/计数类组件。

    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;
    

    【讨论】:

      【解决方案2】:

      来自Hooks FAQ page的反应:

      我应该使用 Hooks、类还是两者兼而有之?
      当你准备好后,我们鼓励你开始在新组件中尝试 Hooks 写。确保团队中的每个人都同意使用它们,并且 熟悉本文档。我们不建议重写您的 现有的类到 Hooks 除非你打算重写它们 (例如修复错误)。

      你不能在类组件中使用 Hooks,但是你可以 绝对将类和函数组件与 Hooks 混合在一起 树。组件是使用 Hooks 的类还是函数 该组件的实现细节。 从长远来看,我们 希望 Hooks 成为人们编写 React 组件的主要方式

      要回答您的问题,等效的类组件是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-10
        • 2020-05-02
        • 2020-10-15
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 2020-07-07
        • 2020-02-05
        相关资源
        最近更新 更多