【问题标题】:Call React Custom Hook from a function从函数调用 React 自定义 Hook
【发布时间】:2021-09-22 02:04:19
【问题描述】:

我正在编写一个从服务器获取数据的钩子(调用 API)。这个钩子应该在一个组件被加载时被调用,并且当一个按钮被点击时,该按钮存在于同一个组件中。 (实际上我在 ReactNative 中使用它,我希望在刷新时调用钩子,但为了简单起见,我在这里按下按钮)

这是我的钩子:

export default function useApi() {
    const [data, setData] = useState({ loading: false, error: null, data: undefined });

    useEffect(() => {
        callApi();
    }, []);

    const callApi = async () => {
        let response;
        try {
            setData({ ...data, loading: true });
            response = await axios.get("url");
        } catch (e) {
            setData({ ...data, loading: false, error: e });
        } finally {
            setData({
                    ...data,
                    loading: false,
                    data: response.data,
                });
        }
    };
    return data;
};

我的组件:

导出默认函数 SpecialComponent() {

const { loading, error, data } = useApi();

const getData = () => {
 //I need to get data using the hook here.
};

return (
   <div>
       { !loading && 
          <div>
              <div>{JSON.stringify(data)}</div> 
              <Button onClick={getData}>Got latest data</Button>
          </div>
       }

       { loading && <div>Loading...</div> }
   </div>
);

}

我考虑过 useEffect 但同样的问题。我不确定从 useEffect 调用钩子是否是正确的模式。

非常感谢任何帮助。

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    也从钩子中返回 callApi 函数。

    export default function useApi() {
        const [data, setData] = useState({ loading: false, error: null, data: undefined });    
        const callApi = async () => {
            let response;
            try {
                setData({ ...data, loading: true });
                setData({
                    ...data,
                    loading: false,
                    data: await axios.get("url").data
                });
            } catch (e) {
                setData({ ...data, loading: false, error: e });
            }
        };
        useEffect(callApi, []);
        return { data, callApi };
    };
    
    export default function SpecialComponent() {
        const { callApi, data } = useApi();
        const { loading, error, data } = data;
        return (
            <div>
                { loading
                    ? <div>Loading...</div>
                    : <div>
                        <div>{JSON.stringify(data)}</div>
                        <Button onClick={callApi}>Got latest data</Button>
                    </div>
                }
            </div>
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 2023-02-19
      • 1970-01-01
      • 2020-10-26
      • 2021-03-20
      • 2020-08-26
      • 2019-10-21
      • 2022-08-07
      相关资源
      最近更新 更多