【问题标题】:Why does componentDidMount fires in a HOC where as componentDidUpdate does not fire?为什么 componentDidMount 在没有触发 componentDidUpdate 的 HOC 中触发?
【发布时间】:2021-08-05 18:52:48
【问题描述】:

我正在关注关于高阶组件(HOC)的 reactjs 教程。我想要一个 HOC 在道具更改时记录道具。

import React, { useState } from 'react';

function logProps(WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      console.log("Component was mounted");
    }
    componentDidUpdate(prevProps) {
      console.log("Current props: ", this.props);
      console.log("Previous props: ", prevProps);
    }
    render() {
      // Wraps the input component in a container, without mutating it. Good!
      return <WrappedComponent {...this.props} />
    }
  }
}

class CustomDivElement extends React.Component{
  render(){
  return <div>{this.props.text}</div>
  }
}

function App(props) {
  const [text, setText] = useState("");
  const EnhancedComponent = logProps(CustomDivElement);
  return (
    <div tabIndex="0" className="App ui container">
      <input
      type="text"
      value={text}
      onChange={(e) => setText(e.target.value)} />
      <EnhancedComponent text={text} />
    </div>
  )
}

export default App

起初我以为是因为我使用的是 HOC。所以我介绍了另一种生命周期方法componentDidMount,它正在触发。 componentDidUpdate 没有触发,这是为什么呢?

【问题讨论】:

  • 我可能会说废话,因为我也在学习 React/JS,但是 const 在函数外部(本地/全局 const)内部是否有不同的含义,就像在 C++ 中一样?你会尝试在 App() 函数之外创建你的 EnhancedComponent 吗?编辑:aaaaand Denis bellow 证实了我的想法 ^^

标签: reactjs react-hoc


【解决方案1】:

因为您在每次渲染时都卸载组件,所以组件不会到达componentDidUpdate 生命周期。

function App(props) {
  // Remount on every render
  const EnhancedComponent = logProps(CustomDivElement);
  ...
}

相反,当使用 HOC 或任何其他组件时,您希望安装一次:

// export default logProps(CustomDivElement)
const EnhancedComponent = logProps(CustomDivElement);

function App(props) {
  const [text, setText] = useState("");
  return (
    <div tabIndex="0" className="App ui container">
      <input
      type="text"
      value={text}
      onChange={(e) => setText(e.target.value)} />
      <EnhancedComponent text={text} />
    </div>
  )
}

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2021-06-21
    • 2019-02-19
    • 2023-03-11
    相关资源
    最近更新 更多