首页 > 解决方案 > 具有使用 Hooks 的能力的 React Native Helper 功能组件

问题描述

我正在用 React Native 编写一个辅助组件。问题是它不允许我在其中使用钩子。

在此处输入图像描述

我见过一些人们建议使用类而不是功能组件的线程。但是 Classes 也不允许使用 Hooks。

这是我的代码:

import React, {useEffect, useState} from 'react'; 
import * as Constants from '../config/Constants';  
import * as SecureStore from 'expo-secure-store';
import { useDispatch, useSelector } from 'react-redux';
import { setUser } from '../store/slices/userSlice';
import axios from 'axios';

// import { Container } from './styles';

const UserHelper = async () => {

    // const { colors }            = useTheme();
    // const [user, setLocalUser]  = useState(); 
    const [loading, setLoading] = useState(true); 
    const [token, setToken]     = useState();
    const user                  = useSelector((state) => state.user);
    
    // ======= my await function here which returns a dataset

    const response = await axios.post(
      "https://MY_ENDPOINT.execute-api.us-east-1.amazonaws.com/v1/",
      API_GATEWAY_POST_PAYLOAD_TEMPLATE,
      { headers }
    );

    return response;
    
};

export default UserHelper;

那么如何定义一个 RN 助手类或功能组件,其中有几个函数可以使用钩子。

标签: reactjsreact-native

解决方案


我听取了@Francesco Clementi 的建议并创建了一个自定义钩子,它就像一个魅力。谢谢弗朗西斯科


推荐阅读