我在网站上的各个地方都有一个预告片列表。在主页和部分页面上。如果您单击预告片,则相关预告片的(详细)信息必须显示在叠加层中。
GraphQL 查询:
query ProductId($id: ID!) {
productById(id: $id) {
id
title
}
}
我创建了一条路线<Route path="*" component={Product} />
:
<Layout>
<Switch>
<Route path={SearchPage} component={Search} exact />
<Route path="*" component={CustomPages} />
<Route path="*" component={Product} />
</Switch>
</Layout>
在<Teaser />
组件中我有一个链接:
const urlQuery = queryString.parse(location.search);
return `${location.pathname}?${queryString.stringify({ ...urlQuery, productId })}`;
然后在<Product />
组件内部,我从 url 中 grep id 并将其用于查询变量以获取正确的数据(基于 id):
import queryString from 'query-string';
import { useLocation } from 'react-router-dom';
const location = useLocation();
const queryParams = queryString.parse(location.search);
const id = queryParams.productId as string;
const { data } = useQuery<GqlRes, ProductArgs>(GET_PRODUCT, {
variables: {
productId: id,
},
errorPolicy: 'all',
});
这里我使用了查询参数。这是正确的方法还是使用路由器参数更好,例如<Route path='/products/:id' component={Product} />
?有哪些选择以及需要考虑的利弊?