首页 > 解决方案 > 对 useEffect 感到困惑

问题描述

我正在构建我的第一个 Custom React Hook,并且对我认为代码的一个简单方面感到困惑:

export const useFetch = (url, options) => {
  const [data, setData] = useState();
  const [loading, setLoading] = useState(true);
  const { app } = useContext(AppContext);
  console.log('** Inside useFetch: options = ', options);

  useEffect(() => {
    console.log('**** Inside useEffect: options = ', options);
    const fetchData = async function() {
      try {
        setLoading(true);
        const response = await axios.get(url, options);
        if (response.status === 200) {
          setData(response.data);
        }
      } catch (error) {
        throw error;
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  return { loading, data };
};

我传递给useFetch两个参数:一个 url 和一个headers包含 AWS Cognito 授权密钥的对象,如下所示:(Authorization: eyJraWQiOiJVNW...为简洁起见)

当我这样做时,options对象确实存在于内部附近useFetch但在useEffect构造内部它是空的。然而,url字符串在两种情况下都正确填充。

这对我来说毫无意义。可能有人知道为什么会这样吗?

标签: javascriptreact-hooksuse-effect

解决方案


下面的代码实现显示它按预期工作。

async/await 已转换为 Promise,但应该具有相同的行为。

“Inside use fetch”输出3次:

  1. 在安装 ( useEffect(()=>..., [])
  2. 第一次状态改变后 ( setLoading(true))
  3. 第二次状态变化后 ( setLoading(false))

并且“内部使用效果”在 mount ( useEffect(()=>..., [])时输出 1 次

由于这种方式对您不起作用,这可能意味着当组件安装时,选项尚不可用。

当您说当您将选项作为依赖项时,您确认了这一点,useEffect 被调用两次,第一次获取失败(很可能是因为缺少选项)。

我很确定您会发现使用自定义挂钩的组件父项中的选项存在问题。

const axios = {
    get: (url, options) => {
      return new Promise(resolve => setTimeout(() => resolve({ status: 200, data: 'Hello World' }), 2000));
    }
  };
  
  const AppContext = React.createContext({ app: null });
  
  const useFetch = (url, options) => {
    const [data, setData] = React.useState();
    const [loading, setLoading] = React.useState(true);
    const { app } = React.useContext(AppContext);
    console.log('** Inside useFetch: options = ', JSON.stringify(options));
  
    React.useEffect(() => {
      console.log('**** Inside useEffect: options = ', JSON.stringify(options));
      const fetchData = function () {
          setLoading(true);
          const response = axios.get(url, options)
            .then(response => {
              if (response.status === 200) {
                setData(response.data);
              }
              setLoading(false);
            })
            .catch(error => {
              setLoading(false);
              throw error;
            });

      };
      fetchData();
    }, []);
  
    return { loading, data };
  };
  
  const App = ({url, options}) => {
    const { loading, data } = useFetch(url, options);
    return (
      <div
          style={{
              display: 'flex', background: 'red',
              fontSize: '20px', fontWeight: 'bold',
              justifyContent: 'center', alignItems: 'center',
              width: 300, height: 60, margin: 5
          }}
      >
        {loading ? 'Loading...' : data}
      </div>
    );
  };
  
  ReactDOM.render(
    <App
        url="https://www.dummy-url.com"
        options={{ headers: { Authorization: 'eyJraWQiOiJVNW...' } }}
    />,
    document.getElementById('root')
  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root" />


推荐阅读