我有一些引导卡。单击它们后,我将重定向到另一个页面,在该页面中我使用通过 NavLink 传递的数据并进行渲染。
这是我的代码。
目的地.jsx
<div className="row mt-3">
{firstRowData.map((country, index) => (
<div className="col-md-3" key={index}>
<NavLink to={`/country/${country.id}`}
state={{ data: country.id }} >
{ Card code }
</NavLink>
</div>
))}
</div>
CountryInfo.jsx
import React from "react";
import { useLocation} from "react-router-dom";
import countryData from "./data";
function CountryInfo() {
const location = useLocation();
let countryId = location.state?.data;
if (countryData) {
const image1Url = countryData[countryId].images.image1;
console.log("Image1 -->", image1Url);
return (
<div className="">
<img
src={image1Url}
alt=""
style={{ height: "100vh", width: "100vw" }}
/>
</div>
);
我有一个包含 json 数据的 data.jsx 文件。
const data = [
{
id: 0,
name: "Singapore",
url: "images/card_singapore.jpg",
price: "$ 300",
day: 5,
images: {
image1: "images/new_0.jpg",
image2: "images/new_1.jpg",
image3: "images/new_2.jpg",
image4: "images/new_3.jpg",
},
},
// some more data.....
通过下面的代码我可以打印正确的图像地址。
console.log("Image1 -->", image1Url);
但是
img
标签无法渲染图像。为什么会出现这种情况?
一个观察:
如果我直接从
contryInfo.jsx
调用 App.js
那么我就可以看到图像。 img
标签正确渲染图像
function App() {
return (
<BrowserRouter>
<CountryInfo />
<Pages />
</BrowserRouter>
);
}
图像源路径使用relative路径,因为它们不以
"/"
字符开头,例如它们是当前 URL 路径“相对”的源。当您在应用程序的根目录渲染 CountryInfo
时,(假设)路径只是
"/"
,因此 PUBLIC 目录中的相对路径有效,例如"/public/images/new_0.jpg"
,但是当 CountryInfo
在 "/country/:countryId"
上渲染时,图像的来源相对于 this路径,例如
/public/country/0/images/new_0.jpg"
。更新数据以使用绝对路径:
const data = [
{
id: 0,
name: "Singapore",
url: "/images/card_singapore.jpg",
price: "$ 300",
day: 5,
images: {
image1: "/images/new_0.jpg",
image2: "/images/new_1.jpg",
image3: "/images/new_2.jpg",
image4: "/images/new_3.jpg",
},
},
...
];
或者在渲染时将其添加到图像源字符串之前:
function CountryInfo() {
const location = useLocation();
const countryId = location.state?.data;
if (countryData) {
const image1Url = countryData[countryId].images.image1;
return (
<div className="">
<img
src={`/${image1Url}`}
alt="country"
style={{ height: "100vh", width: "100vw" }}
/>
</div>
);
...
附加说明:由于导航时
country.id
已在 URL 路径中使用,因此在路由状态中仅传递
相同的country.id
值没有任何意义。只需使用路径段即可获取传递的国家/地区 ID。定义路线渲染CountryInfo
以具有动态路径段,例如path="/country/:countryId"
。示例:
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/country/:countryId" element={<CountryInfo />} />
<Route path="/" element={<Pages />} />
</Routes>
</BrowserRouter>
);
}
<div className="row mt-3">
{firstRowData.map((country) => (
<div className="col-md-3" key={country.id}>
<NavLink to={`/country/${country.id}`}>
{ ...Card code... }
</NavLink>
</div>
))}
</div>
import { useParams } from 'react-router-dom';
function CountryInfo() {
const countryId = useParams();
const { image1, name } = countryData[countryId]?.images ?? {};
if (image1) {
return (
<div className="">
<img
src={image1}
alt={name}
style={{ height: "100vh", width: "100vw" }}
/>
</div>
);
...