简体   繁体   中英

Dynamic routes to child components

My case is related with routing. I have n of users in my app. Listed in an unordered list. Each li element is a Link :

<Link to={{ pathname: `user/${user.id}`, state: { user } }}>

Route code:

{
  path: 'user/:id',
  name: 'userDetails',
  getComponent(nextState, cb) {
    import('app/UserDetails')
      .then(loadModule(cb))
      .catch(errorLoading);
  },
}

Okey, so I want to pass to the component the user object, which holds all info needed to be displayed in the user details component.

As you can see, I've done it with state argument passed inside to prop in the Link element. It works fine, however it fails when I copy and paste the direct link to the component in new tab.

/user/1 - page fails to load because state is undefined (it's not being passed properly through Link .

My question is : How to do it properly? I guess it isn't the rightest way to do it.

Note that I could just connect it with redux, take the param from the props - id and search whole users array of objects for that particular object with id === 1 , but does it make sense? Im sure there must be some easier way to fix it. Thank you in advance!

ReactRouter state object should be used for temporary data related to location transitions in the scope of the app . Here is a perfect example from the docs:

state: { fromDashboard: true })

It's just a simple flag. Temporary state which is not really important for your application global state.

When you open URL directly or come from other sites - there is no transition created, so that state object doesn't exist and your solution will never work.

Your second approach is correct.

Don't mix responsibilities of the modules. React router is responsible for routing and another module should provide the state. Possibility to inject some data into the router doesn't mean that you should use it as a data provider. It makes hard debugging, logging and mocking data for tests.

Ask yourself why are you using Redux? Probably to keep your state clean, readable and predictable . So why are you trying to avoid using it with some smart tricks? In your example you already created completely separated state out of sync with application state. That approach will bite you.

You can play with Higher Order Components to manage state and passing props down (but always from one single source of truth (could be Redux...)), or just use simpler or more abstracted state manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM