【问题标题】:Describing React componentDidMount() in Meteor js syntax用 Meteor js 语法描述 React componentDidMount()
【发布时间】:2021-05-12 15:44:16
【问题描述】:

如何在不创建类扩展反应组件的情况下声明 componentDidMount?例如 render() 用 react-dom 包声明,也许是存在另一个 componentDidMount 包?

class App extends Component {
  constructor(){
    // do something
  }
  componentDidMount(){
    // js code must run after page loaded
  }
  render(){
    return(
      <div className="app">

      </div>
    );
  }
}
export {App};

与组件构造函数()相同

const App = () => {

  // constructor and componentDidMount does not work here

  // js code must run after page loaded

  return (
    <div className="app">

    </div>
  );
};
export {App};

【问题讨论】:

  • 另一种不使用“扩展组件”来编写 React 组件的方法是使用 React Hooks。您可以在其中编写类似于第二个示例的功能组件,而无需构造函数或 componentDidMount()。 reactjs.org/docs/hooks-intro.html。据我所知,如果不使用“扩展组件”,就无法使用这些功能
  • 这是在reactjs.org/docs/hooks-effect.html 中回答的。

标签: reactjs meteor


【解决方案1】:

首先,您想要实现的是完全独立于 Meteor 的。这是任何后端都可能存在的纯 React 问题。您可以使用 useEffect() 挂钩来完成您想要实现的目标,您可以在此处找到相关文档:

https://reactjs.org/docs/hooks-reference.html#useeffect

这是一篇很棒的文章,解释了如何用钩子替换生命周期方法:

https://dev.to/trentyang/replace-lifecycle-with-hooks-in-react-3d4n

在您的情况下,对于 componentDidMount,您必须执行以下操作:

useEffect(() => {
     // js code must run after page loaded
}, []);

在最终的数组中,你必须放置依赖项,如果你需要,它将重新触发钩子。模拟一个简单的 componentDidMount 一个空数组通常是解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多