Pass object through Link in react router

做~自己de王妃 提交于 2019-11-27 01:40:58
knowbody

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.

The problem comes when the user accesses the url which is used in Link then there is no way to get the data.

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.

Or if the data is not in the Store call the action to fetch the data from the API.

No, you can't pass an object in params, so I would agree with you that your best plan is to pass the id to a store, have the store emit a CHANGE event, and have components query the store for info.

It is possible to pass an object through a Link. Add your data within a query rather than params and stringify the object:

<Link to={{ 
  pathname: `/blog/${post.id}`, 
  query: {
    title: post.title, 
    content: post.content,
    comments: JSON.stringify(post.comments)
  } 
}}>Read More...</Link>

Then in your child component parse the string back in to an object:

JSON.parse(this.props.comments)

This isn't possible, you need to pass something that can be stored in the URL such as a string ID. You would then use that ID to perform a lookup of the object.

You could try JSON serializing it and then de-serializing it on the receiving end.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!