在使用钩子加载数据之前停止渲染

时间:2020-06-29 08:30:35

标签: reactjs react-hooks

我是React钩子的新手,我编写了react定制钩子

挂钩:

./configure --without-readline --without-zlib

我还编写了一个功能组件,我想在数据到来时呈现组件 这是我的组件

组件

 import { useState, useEffect } from 'react';

 export const useFetch = (url, options) => {
 const [response, setResponse] = useState(null);
 const [error, setError] = useState(null);
  useEffect(() => {
 const fetchData = async () => {
  try {
    const res = await fetch(url, options);
    const json = await res.json();
    setResponse(json);
  } catch (error) {
    setError(error);
  }
};
fetchData();
 }, []);
 return { response, error };
};

但是我无法渲染List组件,一旦数据来自后端,我便不明白为什么为什么列表笔记中的数据仍然具有空值并且列表仍未呈现

我从后端得到了正确的值

1 个答案:

答案 0 :(得分:0)

useFetch返回return { response, error }; ==> const response = useFetch('http://localhost:8080/test', {}); response是包含 { response, error }的对象

请改为const {response} = useFetch('http://localhost:8080/test', {});

您应该处理useFetch

中的加载

UseFetch

import { useState, useEffect } from 'react';

export const useFetch = (url, options) => {
 const [response, setResponse] = useState(null);
 const [error, setError] = useState(null);
 const [loading, setLoading] = useState(true);
 useEffect(() => {
 const fetchData = async () => {
  try {
    const res = await fetch(url, options);
    const json = await res.json();
    setResponse(json);
    setLoading(false)
  } catch (error) {
    setError(error);
    setLoading(false)
  }
 };
 fetchData();
}, []);
 return { response, error,loading };
};

订阅

import React, { useState, useEffect } from 'react';
import './index.scss';
import { List } from '../components';
mport { useFetch } from '../../hooks';


export const Subscription = () => {
 const {response: subscriptions, loading} = useFetch('http://localhost:8080/test', {});
return (
  <div>
    {isLoading && <div>Loading...</div>}
    {!isLoading && (
      <div className="list">
         <List subscriptions={subscriptions} />
      </div>
     )}
 </div>
 );
};