在React应用程序中使用React路由器使用React路由器来获取数据是一种不正确的做法吗?
在我的应用中,我有一个home
页面,该页面有一个名为帖子
的孩子以以下方式设置路线:
<Route path='/' element={<Home />}>
<Route path='/posts/popular' element={<Posts />} />
<Route path='/posts/new' element={<Posts />} />
</Route>
我想将其设置流行
路径,那么我的API调用将是:
axios.get('/posts?sort=-popular')
但是,如果我在新呼叫中,则该调用是:
axios.get('/posts?sort=-createdAt')
我想实现的方式是将第二个参数变成选择器,例如:
<Route path='/' element={<Home />}>
<Route path='/posts/:sortBy' element={<Posts />} />
</Route>
// in my Posts component I would call useParams
const {sortBy} = useParams();
// then in useEffect
axios.get(`/posts?sort=-${sortBy})
但是这让我感到沮丧,就像我做错了。实施此功能的更好方法(如果有的话)是什么?
In my app I have a Home
page that has a child named Posts
the routes are set up in the following manner:
<Route path='/' element={<Home />}>
<Route path='/posts/popular' element={<Posts />} />
<Route path='/posts/new' element={<Posts />} />
</Route>
I would like to set it up where if I am on the popular
path then my api call will be:
axios.get('/posts?sort=-popular')
But if I am on new, then the call would be:
axios.get('/posts?sort=-createdAt')
The way I was thinking of implementing it was to make the second param into a selector like:
<Route path='/' element={<Home />}>
<Route path='/posts/:sortBy' element={<Posts />} />
</Route>
// in my Posts component I would call useParams
const {sortBy} = useParams();
// then in useEffect
axios.get(`/posts?sort=-${sortBy})
But this feels off, like I am doing it wrong. What is a better way, if any, of implementing this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所做的是可以的,但是它将使组件更难重复使用,同样,如果您更改路径,则需要更改组件
posts
。最好在组件 ports 中添加新的Propsortby
,然后在ROUTE> ROUTE> ROUTE
组件中传递道具。What you did is ok, but it will make the component harder to reuse, also if you changed the path you will need to change also the component
Posts
. It’s better to add a new propsortBy
inside your componentPosts
and pass the prop inside yourRoute
component.您可以将道具传递到
route> ROUTE> ROUTE>中的
&lt; posts/&gt;
组件中。这是一个示例:
然后在
帖子
内部您可以使用道具来确定要进行的呼叫:You can pass props into the
<Posts />
component in yourRoute
.Here's an example:
Then inside
Posts
you can use the prop to determine which call to make: