我正在尝试根据主页组件的项目列表中的产品 ID 从我的主页路由到组件“产品”。我的页面被路由到“localhost:3000/id”,但没有获取产品组件。我没有遇到任何错误。我从假 API 中获取数据并将产品显示在主页上。单击产品后,我希望页面路由到“产品”组件。地址按预期路由,但组件未加载。
import React, { Component } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Products from "./Products";
interface Props {}
interface ResponseData {
id: number;
price: number;
description: string;
image: string;
}
interface State {
response: ResponseData[];
}
export default class Home extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
response: [],
};
}
getProductsData = async () => {
const apiResponse = await fetch("https://fakestoreapi.com/products");
console.log(apiResponse);
const responseData = await apiResponse.json();
this.setState({
response: responseData,
});
};
componentDidMount() {
this.getProductsData();
}
render() {
const { response } = this.state;
if (response.length === 0) {
return <div className="loader">Loading the items....... </div>;
}
return (
<div >
<div className="product-list">
{response.map((resp) => (
<Switch>
<Link className = "product-cards"
to={`${resp.id}`} >
<Route path={`${resp.id}`} component={Products}/>
<div className="product-cards">
<img src={resp.image} />
<div className="product-description">{resp.description}</div>
<div className="product-price">{resp.price}</div>
</div>
</Link>
</Switch>
))}
</div>
</div>
);
}
}
最佳答案
您可能需要替换到应用程序组件的切换路由,并且在此主页组件中只需使用链接重定向到您想要的路径。
function App() {
return (
<Switch>
<Route exact path="/" component={ Home } />
<Route path="/:id" component={ Products } />
</Switch>
);
}
Home 组件返回应该是这样的:
return (
<div className="product-list">
{response.map((resp) => (
<Link
className = "product-cards"
to={`/${resp.id}`}
>
<div className="product-cards">
<img src={resp.image} />
<div className="product-description">{resp.description}</div>
<div className="product-price">{resp.price}</div>
</div>
</Link>
))}
</div>
);
关于javascript - 无法使用 React-Router-DOM 路由到所需的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69204097/