首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用和编写React Hooks

使用和编写React Hooks
EN

Stack Overflow用户
提问于 2021-08-27 18:56:33
回答 1查看 31关注 0票数 0

我有这个组件:

代码语言:javascript
复制
            import React, { Component } from 'react';
        import useFetch  from "../useFetch";

        export class Patient extends Component {
          static displayName = Patient.name;

          constructor(props) {
            super(props);
          }

            componentDidMount() {

                alert("fgggg");
                const { isLoading, serverError, apiData } = useFetch(
                    "/Patient/GetPatients"
                );


            }

          render() {
            return (
              <div>
              </div>
            );
          }
        }

我想调用useFetch,这是我的useFetch:

代码语言:javascript
复制
            import React, { useEffect, useState } from "react";

        function useFetch(url){
            const [isLoading, setIsLoading] = useState(false);
            const [apiData, setApiData] = useState(null);
            const [serverError, setServerError] = useState(null);

            alert("dddd");
            useEffect(() => {
                setIsLoading(true);
                const fetchData = async () => {
                    try {
                        fetch(url)
                            .then(response => response.json())
                            .then(data => setApiData(data));

                        //const resp = await axios.get(url);
                        //const data = await resp?.data;

                        setIsLoading(false);
                    } catch (error) {
                        alert(error);
                        setServerError(error);
                        setIsLoading(false);
                    }
                };

                fetchData();
            }, [url]);

            return { isLoading, apiData, serverError };
        };
        export default useFetch;

错误:

代码语言:javascript
复制
Attempted import error: 'useFetch' is not exported from '../useFetch'.

有人能给点建议吗?

更新

感谢答案中的资源,但我找到了这个https://blog.bitsrc.io/fetching-data-in-react-using-hooks-c6fdd71cb24a

现在我把我的代码改成这样:

代码语言:javascript
复制
            import React, { useEffect, useState } from "react";

        export default function useFetch(url, opts){
                const [response, setResponse] = useState(null)
                const [loading, setLoading] = useState(false)
                const [hasError, setHasError] = useState(false)
                useEffect(() => {
                    setLoading(true)
                    fetch(url, opts)
                        .then((res) => {
                            setResponse(res.data)
                            setLoading(false)
                        })
                        .catch(() => {
                            setHasError(true)
                            setLoading(false)
                        })
                }, [url])
                return [response, loading, hasError]
        }

代码语言:javascript
复制
            import React, { Component } from 'react';
        import useFetch from "../useFetch";

        export class Patient extends Component {
          static displayName = Patient.name;

          constructor(props) {
            super(props);
          }

            componentDidMount() {

                alert("fgggg");
                const [ response, loading, hasError ] = useFetch("", "");


            }

          render() {
            return (
              <div>
              </div>
            );
          }
        }

我仍然得到这个错误

代码语言:javascript
复制
×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
EN

回答 1

Stack Overflow用户

发布于 2021-08-27 19:08:38

您可以在定义函数/钩子时导出,而不是在文件末尾导出。

代码语言:javascript
复制
export default function useFetch(url) {
  const [isLoading, setIsLoading] = useState(false);
  const [apiData, setApiData] = useState(null);
  const [serverError, setServerError] = useState(null);

  alert("dddd");
  useEffect(() => {
    setIsLoading(true);
    const fetchData = async () => {
      try {
        fetch(url)
          .then((response) => response.json())
          .then((data) => setApiData(data));

        //const resp = await axios.get(url);
        //const data = await resp?.data;

        setIsLoading(false);
      } catch (error) {
        alert(error);
        setServerError(error);
        setIsLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { isLoading, apiData, serverError };
}

还要仔细检查您的导入路径是否正确。

创建自定义钩子并使用它们时的很好参考:https://www.freecodecamp.org/news/how-to-create-react-hooks/

更新:正如Hozeis所说。不能在类组件中使用钩子。刚刚注意到您使用的是一个类组件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68958181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档