繁体   English   中英

React Native 使用钩子函数和组件

[英]React Native using hooks functions and components

我有一个 React Native 项目。 我是 React Native 的新手,我试图从我的 UserInfo.js 中提供的代码中确定它是否应该被分类并用作组件、辅助函数或挂钩

// UserInfo.js
import {useEffect} from 'react';
import {Alert, NativeEventEmitter, NativeModules} from 'react-native';

const userInfoEvents = new NativeEventEmitter(
  NativeModules.ReactNativeSwiftBridge,
);

export const UserInfoAlert = () => {
  useEffect(() => {
    const userInfoMenuListener = userInfoEvents.addListener('onMenu', data => {
      if (data.type === 'UserInfo') {
        Alert.alert(data.message);
      }
    });

    return () => {
      userInfoMenuListener.remove();
    };
  }, []);

  return null;
};

export default UserInfoAlert;

// App.js
const App = () => {
    // other stuff here

    // should it be a hook or function

    return(
        <Navigation>
            <Stack.screen component={{/* */}} />

            {/* Should it be a component */}
        </Navigation>
    )
};

export default App

它不返回任何东西,所以它不是一个组件。

它调用一个 React 钩子,所以它只能在 React 组件或其他钩子的顶层被调用 - 所以它应该被称为自定义钩子,而不是(更一般的)辅助函数。 因此,它的名称可能应该是useUserInfoAlert ,以符合 React 的钩子名称约定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM