Programmatically navigate using react router

后端 未结 30 2988
無奈伤痛
無奈伤痛 2020-11-21 05:18

With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls t

30条回答
  •  耶瑟儿~
    2020-11-21 05:39

    For this one, who does not control the server side and because of this is using hash router v2:

    Place your history into separate file (e.g. app_history.js ES6):

    import { useRouterHistory } from 'react-router'
    import { createHashHistory } from 'history'
    const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });
    
    export default appHistory;
    

    And use it everywhere!

    Your entry point for react-router (app.js ES6):

    import React from 'react'
    import { render } from 'react-dom'
    import { Router, Route, Redirect } from 'react-router'
    import appHistory from './app_history'
    ...
    const render((
      
      ...
      
    ), document.querySelector('[data-role="app"]'));
    

    Your navigation inside any component (ES6):

    import appHistory from '../app_history'
    ...
    ajaxLogin('/login', (err, data) => {
      if (err) {
        console.error(err); // login failed
      } else {
        // logged in
        appHistory.replace('/dashboard'); // or .push() if you don't need .replace()
      }
    })
    

提交回复
热议问题