简体   繁体   中英

React dynamic routes and refresh

I am new to react routes and I am writing simple blog collection. I have provided router in index.js

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <App />
    </Router>
  </Provider>,
  document.getElementById('root')
)

I have routes in my app.js

  return (
    <div style={{marginLeft:'20px'}}>
      <Route path='/'>
        {loggedUser ? <Bar/> : null}
        {loggedUser ? <h2>Blogs</h2> : null}
        {loggedUser ? <Redirect to='/blogs'/> : <Redirect to='/login'/>}
      </Route>
      <Route path='/login'><LoginForm/></Route>
      <Route exact path='/blogs'>
        <BlogList/>
        {visibility ? <BlogForm/> : null}
      </Route>
      <Route exact path='/users'><UserList/></Route>
      <Route path='/users/:id'><SingleUser/></Route>
      <Route path='/blogs/:id'><SingleBlog/></Route>
    </div>
  )

If user navigates to route with id like '/blogs/:id', it works fine. But user can refresh browser and then id disappears from address bar and application drops back to '/blogs'. How to prevent this behaviour?

it's better to see first react-router-nesting it explained perfectly and on the other hand if you have many route create a array

const Routes = [
  { 
    component:BlogList,
    path:'/blogs,
    exact:true
  },
  { 
    component:UserList,
    path:'/users,
    exact:true,
    routes:[
      {
       component:SingleUser,
       path:'/:id'
      }
     ]
  {
    component: Order,
    path: '/',
    exact: true,
    routes: [
      {
        component: TabBar,
        path: '/',
      },
      {
        component: Menu,
        path: '/',
        exact: true,
      },
      {
        component: InnerRoute,
        path: '/:name',
        routes: [
          {
            path: '/',
            component: Menu,
            exact: true,
          },
          {
            path: '/info',
            component: InfoRest,
          },
          {
            path: '/favorite',
            component: Favorite,
          },
        ],
      },
    ],
  },
];

and in the file you wana to use it write following code

      <Router history={browserHistory}>
        <Switch>{renderRoutes(Routes)}</Switch>
      </Router>

import renderRoutes from react-router-config for routes or map it and return each other

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