我是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组件,一旦数据来自后端,我便不明白为什么为什么列表笔记中的数据仍然具有空值并且列表仍未呈现
我从后端得到了正确的值
答案 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>
);
};