通过反应路由器中的链接传递对象 [英] Pass object through Link in react router
问题描述
是否可以通过 react-router 中的 Link
组件传递对象?
Is it possible to pass an object via Link
component in react-router?
类似于:点击链接>
Something like:
<Link to='home' params={{myObj: obj}}> Click </Link>
就像我将 props
从 Parent
传递给 Child
组件一样.
In the same way as I would pass props
from the Parent
to Child
component.
如果不可能,那么实现这一目标的最佳方法是什么:
我有一个 React + Flux 应用程序,我用一些数据渲染了表格.我想要做的是当我单击其中一行时,它会将我带到该行的某些 details 组件.该行包含我需要的所有数据,所以我认为如果我可以通过 Link
传递它会很棒.
If it's not possible what is the best way of achieving this:
I have a React + Flux app, and I render the table with some data. What I am trying to do is when I click on one of the rows it would take me to some details component for this row. The row has all of the data I need so I thought it would be great if I could just pass it through Link
.
另一种选择是在 url 中传递行的 id
,在 details 组件中读取它并从商店请求按 ID 的数据.
The other option would be to pass the id
of the row in the url, read it in the details component and request the data from the store for by ID.
不确定实现上述目标的最佳方法是什么...
Not sure what is the best way of achieving the above...
推荐答案
所以我对这个问题的最终结论是我没有好好考虑.通过 Link
传递我的数据似乎很自然,这样我就可以在我的 Child
组件中访问它们.正如 Colin Ramsay 所提到的,Link 中有一种叫做
代码> 但这不是这样做的方法.当数据通过 state
的东西Link
传递时,只有当用户点击某物并被带到 Child
组件时,它才能正常工作.
So my final conclusion on this question is that I didn't think it through properly. It seemed natural just to pass my data through the Link
so I can access them in my Child
component. As Colin Ramsay mentioned there is something called state
in the Link
but that's not the way to do it.
It would work fine when the data is passed through Link
only if the user clicks on something and is taken to the Child
component.
问题出现在用户访问Link
中使用的url
时,就无法获取数据.
The problem comes when the user accesses the url
which is used in Link
then there is no way to get the data.
所以在我的例子中的解决方案是在 Link
参数中传递 ID
然后检查我的 Store
是否有数据(用户访问它通过 Link
) 然后从 Store
获取这些数据.
So the solution in my case was to pass the ID
in Link
params and then check if my Store
has the data (user accesses it via Link
) and then getting this data from the Store
.
或者如果数据不在 Store
中,则调用 action
从 API 中获取数据.
Or if the data is not in the Store
call the action
to fetch the data from the API.
这篇关于通过反应路由器中的链接传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!