【发布时间】:2021-06-26 02:02:30
【问题描述】:
我正在从 API 获取数据并将数组存储在“产品”变量中,并在尝试使用路由导航到我的页面时引用请求 URL 中的占位符参数,但是当我尝试导航到诸如“http:/”之类的页面时/localhost:3000/shoes/4' 应该返回带有页面未找到文本的页面,而不是详细信息页面。请说明为什么没有发生这种情况。
Json 服务器位于端口 3001
UseFetch.js
import { useState, useEffect } from "react";
const baseUrl = "http://localhost:3001/";
export default function useFetch(url) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`${baseUrl}${url}`)
.then((response) => {
return response.json();
})
.then((data) => {
setData(data);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setLoading(false);
});
}, [url]);
return { data, error, loading };
}
产品数组
{
"id": 1,
"category": "shoes",
"image": "shoe1.jpg",
"name": "Hiker",
"price": 94.95,
"skus": [
{ "sku": "17", "size": 7 },
{ "sku": "18", "size": 8 }
],
"description": "This rugged boot will get you up the mountain safely."
},
{
"id": 2,
"category": "shoes",
"image": "shoe2.jpg",
"name": "Climber",
"price": 78.99,
"skus": [
{ "sku": "28", "size": 8 },
{ "sku": "29", "size": 9 }
],
"description": "Sure-footed traction in slippery conditions."
},
{
"id": 3,
"category": "shoes",
"image": "shoe3.jpg",
"name": "Explorer",
"price": 145.95,
"skus": [
{ "sku": "37", "size": 7 },
{ "sku": "38", "size": 8 },
{ "sku": "39", "size": 9 }
],
"description": "Look stylish while stomping in the mud."
},
{
"id": 4,
"category": "headphone",
"image": "headphone3.jpg",
"name": "headphone red",
"price": 100,
"description": "Red colored headphone"
},
{
"id": 5,
"category": "headphone",
"image": "headphone2.jpg",
"name": "headphone blue",
"price": 90,
"description": "Blue colored headphone"
},
{
"id": 6,
"category": "headphone",
"image": "headphone1.jpg",
"name": "headphone black",
"price": 80,
"description": "Black colored headphone"
}
获取数据到产品数组
const { category, id } = useParams();
const { data: products, error, loading } = useFetch(
`products?category=${category}&id=${id}`
);
如果产品数组为空,则指向未找到的页面
if (products.length === 0) {
return <PageNotFound />;
}
使用路由定向到详细信息页面
<Route path="/:category/:id" element={<Detail />} />
【问题讨论】:
-
似乎路由呈现了一个详细页面,而不是一个未找到的页面,但也许您脱节的 sn-ps 使您难以理解您的代码。你能分享Minimal, Complete, and Reproducible Code Example吗?您能否也澄清一下问题是什么,包括复制步骤?
-
@DrewReese 嘿,我附上了 codesanbox 链接,这里为什么产品变量返回为 null,当我在根页面 url 中输入像 /2 这样的可用 id 时。错误说“无法读取 null 的属性名称”link
标签: javascript reactjs react-hooks react-router-dom fetch-api