reactjs - How to pass props to child component based on dynamic route
问题描述
I'm trying to make an ecommerce website with react and react-router-dom. I have different components: ProductsList
, Product
, Details
(about single product).
I am using Context API in a separate file. My App.js
file looks like this:
...imports
const products = useContext(ProductContext)
const App = () => {
...
<Route path="/products/:id">
<Details products={products} />
</Route>
}
But I want to send details only about the product whose id
matches the dynamic route id, not the whole array of products. But how do I extract that id? I know I can do it inside the Details.jsx
file by using useParams()
. But how do I do that from inside App.js
?
I just noticed there's a similar quesiton. But I want my Details
component in its own file and not inside App
.
解决方案
您可以尝试以下操作:-
...imports
const products = useContext(ProductContext)
const App = () => {
...
<Route path="/products/:id" render={(props) => {
const id = props.match.params.id;
const productData = products.find(product => product.id === id);
return <Details {...props} product={productData} />
}}
</Route>
}
推荐阅读
- javascript - 将数据框从 python/pandas 导出到 javascript
- node.js - 玩笑单元测试的问题,其中模拟值被覆盖
- swift - 如何自定义 UIActivityController?斯威夫特 5
- python - python没有打印3个字母的每一个组合并且丢失了很多
- openshift - OpenShift Playground 4.5 和 4.7 登录
- python - Matplotlib pcolormesh 与 x 轴上的时间和布尔真/假作为着色
- python - 对变量中的数字求和的问题
- flutter - 权限位置不适用于颤振中的所有设备
- tensorflow - 如何将 Optuna 与 Deepspeech 训练集成?
- c# - ASP.NET Core 5 WebAPI - Azure AD - 使用 Azure 广告访问令牌调用图形 API