【发布时间】:2021-07-12 13:23:55
【问题描述】:
我制作了一个 react 项目,在加载数据时,我需要使用 fetch-get 从 json 中获取我的数据。但是,当我这样做时,它首先发送空数组,然后在 1-2 秒后向我发送数据。因此,当它的空数据开始时,我的渲染开始了,所以我的应用程序崩溃了。我怎样才能在没有空数据的情况下做到这一点?我的代码:
const { id } = useParams();
const [articles, setArticles] = useState([]);
const [collection, setCollection] = useState([]);
useEffect(() => {
fetch("http://localhost:3001/api/v1/article/bycollection/" + `${id}`)
.then((x) => x.json())
.then((z) => {
setArticles(z);
}, []);
fetch("http://localhost:3001/api/v1/collection/" + `${id}`)
.then((x) => x.json())
.then((z) => {
setCollection(z);
}, []);
}, [id]);
空错误行:
return (
<div className="tomiddle ">
<div className="mb-3">
<BreadCrumbComp data={breadCrumbData} />
</div>
<div className="collectionBg">
<div className="collectionHeader flex">
<div className="w-32 h-32 p-4 mt-2 text-5xl">
<i className={collection.icon}></i>
</div>
<div>
<h1 className="collectionTitle ">{collection.name}</h1>
<WriterGroupInfo groupData={collection} /> // Here i getting error.
Its sending empty collection
</div>
</div>)
作家组信息:
const WriterGroupInfo = (props) => {
const prop = props.groupData;
console.log("prop=>", props); // Showing empty array.
const articles = prop.articles.slice(0, 3);
const last = articles[articles.length - 1];
const lastAuthor = articles.length > 1 ? " ve " + last.author.name : "";
const authorNames =
articles
.slice(0, 2)
.map((a) => a.author.name)
.join(", ") + lastAuthor;
return (
<div className="flex pt-4 ">
<Avatar.Group>
{articles.map((x) => (
<Avatar key={x.id} src={x.author.avatar} />
))}
</Avatar.Group>
<div className="text-collection-small-500 truncate text-xs pl-2 pt-1">
<span>Bu koleksiyonda {prop.articles.length} makale mevcut</span>
<br />
{articles.length > 0 ? (
<span className="truncate mr-2">
<span className="text-gray-400 ">Yazarlar: </span>
{authorNames}
</span>
) : (
<></>
)}
</div>
</div>
);
};
【问题讨论】:
-
你为什么将一个空数组传递给
.then?你遇到了什么错误?WriterGroupInfo组件是什么样的?等等等等。请提供更多数据,我们无法为您提供更多帮助。 -
@JaredSmith 我在哪里传递空数组?我的数据通常不是空的。等等,兄弟,我将为 writergroupinfo 编辑我的问题,抱歉。
-
@JaredSmith 我编辑。请再检查一遍好吗?
-
您在 fetch 响应处理中传递了一个空数组,这是对 Promise API 的错误使用。
-
@JaredSmith 我实际上不明白我在哪里传递空数据。当我检查像`.then((z) => { console.log(z) // setArticles(z); }, []);` 这样我可以看到我的数据。
标签: javascript node.js reactjs react-native