我在 useEffect() 之外的 console.log 中获取数据,但是当我在网页中使用该数据时,数据不会出现在网页上。这是网页的代码和屏幕截图,下面我们可以看到数据正在餐厅状态传入,但数据没有显示在网页中,我在将该数据提供给网页时在代码中编写的内容有什么问题吗,我被卡住了在过去两天的这一部分中,我们衷心感谢任何帮助
import '../../styles/Rs.css'
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import 'react-tabs/style/react-tabs.css';
import {useParams} from 'react-router-dom'
export default function RestDetails() {
const [restaurant,setRestaurant]=useState({});
let {rName}= useParams();
useEffect(()=>{
fetch(`http://localhost:8089/restaurant/details/${rName}`,{method:'GET'})
.then(response=>response.json())
.then(data=>{setRestaurant(data.data);console.log("the value inside useEffect",restaurant)})
},[])
console.log("the value outside useEffect",restaurant);
// const {name,address,thumb,cost}=restaurant
// const cuisineList=!(Cuisine==undefined) && Cuisine.length && <ul>{
// Cuisine.map(item=><li>{item.name}</li>)
// }</ul>
// console.log("value of restaurant",restaurant);
console.log(typeof(restaurant))
return (
<>
<div className="header">
<span className="logo">e!</span>
<span className="right"> <button className="button1">Login</button>
<button className="button2">Create an account</button></span>
</div>
<div className='photo'><img src={restaurant.thumb} alt="not found" height="350px" width="100%"/></div>
<div className='rsName'>{restaurant.name}</div>
<div>
<Tabs>
<TabList>
<Tab>Overview</Tab>
<Tab>Contact</Tab>
</TabList>
<TabPanel>
<div>About this place</div>
<div>Cuisine</div>
{/* {cuisineList} */}
<div>Average Cost</div>
<div>₹ {restaurant.cost}</div>
</TabPanel>
<TabPanel>
<div>Phone Number</div>
<div>+91 -123456789</div>
<div> {restaurant.name} </div>
<div>{restaurant.address}</div>
</TabPanel>
</Tabs>
</div>
</>
)
}````
您输入错误:
<div className='rsName'>{resaturant.name}</div>
应该是餐厅
如果您要显示来自 API 或 Promise 的数据,请始终用条件包装 JSX。
修复方法如下:
return (
<>
{restaurant && <div className="header">
<span className="logo">e!</span>
<span className="right"> <button className="button1">Login</button>
<button className="button2">Create an account</button></span>
// rest of the HTML
</div>}
</>
)