用功能组件替换类组件中的构造函数

时间:2020-09-29 15:33:47

标签: reactjs react-native react-hooks

预先感谢。

我正在尝试在我的项目上实现React Native推送通知。 因此,我该如何用功能组件替换类组件中的代码。 我使用React Hooks和功能组件

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};

    this.notif = new NotifService(
      this.onRegister.bind(this),
      this.onNotif.bind(this),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我可以通过使用useState钩子设置空对象状态并将notif值包装在带有空依赖项列表的useMemo钩子中,将其转换为功能组件。我对React Native组件没有经验,所以我用useCallback钩子创建了空的回调,以补充您所引用的缺少的类方法。如果这些与React Native API有关,我假设您可以引用等效的钩子导出。

 import React, { useCallback, useMemo, useState } from 'react'
 
 const App = props => {
   const [state, setState] = useState({})
   const onRegister = useCallback(() => {}, [])
   const onNotif = useCallback(() => {}, [])
   
   const notif = useMemo(() => {
     return new NotifService(onRegister, onNotif)
   }, [])

   return (<>render notif.message (if exists): {notif.message}</>)
 }