UseEffect钩子未运行



我试图运行useEffect钩子从json文件中获取数据。但是,useEffect没有运行,因此屏幕显示为空白。这是我试图获取数据并更新状态的代码部分。

const RestaurantLayout = ({ children: Component, ...props }) => {
const [restaurant, setRestaurant] = useState([])
useEffect(() => {
console.log("useEffect called");
fetch('/restaurantData.json')
.then(response => {
console.log(response)
return response.json();})
.then((resData) => {
setRestaurant(resData);
})
.catch(error => console.error(error));
}, [])

json文件在公共文件夹中。

然而,当我找到解决这个问题的方法时,我从json文件中复制了json数据,并手动将其放在useState中,然后useEffect确实运行了。这是代码:

const RestaurantLayout = ({ children: Component, ...props }) => {
const [restaurant, setRestaurant] = useState([
{
_id: "1",
isPro: true,
isOff: false,
name: "Nathu's Sweets",
address: "Ashok Vihar, New Delhi",
restaurantRating: "3.7",
cuisine: [
"North Indian",
"Sweets",
"South Indian",
"Chinese",
"Street Food",
"Fast Food",
"Desserts"
],
costForOne: "350",
images: [
{
"location":
"/tiffin3.jpg"
},
{
"location":
"/foodimg1.jpg"
},
{
"location":
"/foodimg2.jpg"
},

{
"location":
"/foodimg3.jpg"
}
]
},
])
useEffect(() => {
console.log("useEffect called");
fetch('/restaurantData.json')
.then(response => {
console.log(response)
return response.json();})
.then((resData) => {
setRestaurant(resData);
})
.catch(error => console.error(error));
}, [])

我不知道为什么。请帮帮我。

你实际上只能获取一个API端点。您的路径/restaurantData.json不能解析到这样的端点。

必须创建一个apiOR硬编码json数据正如您在第二个代码示例中所做的那样。

首选的方法是创建一个api。你可以使用express.js(仅API)或React框架,如next.js它还支持创建Restful api。

下面是一个示例的next.js api端点,其中json数据被发送:
https://nextjs.org/docs/api-routes/introduction