首頁  >  問答  >  主體

是否可以在react-router中定義預設路由?

<p>假設我的應用程式的基本網址是 <em>example.com/app</em></p> <p>是否可以在react-router中設定基本路由,而不是將所有路由寫為</p> <pre class="brush:php;toolbar:false;">/app/a /app/b /app/c</pre> <p>我可以將它們指定為</p> <pre class="brush:php;toolbar:false;">a b c</pre> <p>我嘗試了在文件中找到的以下範例,但它不起作用(頁面不會顯示任何內容)。也許是因為我使用的是react-router@3.0.0-alpha.1,或是我做錯了什麼。 </p> <pre class="brush:php;toolbar:false;">import { useRouterHistory } 從 'react-router' import { createHistory } from 'history' const history = useRouterHistory(createHistory)({ basename: '/app' }) const Root = ({store}) => ( <Provider store={store}> <Router history={history}> <Route path='/' component={App}> … </Route> </Router> </Provider> )</pre> <p><br /></p>
P粉128563140P粉128563140391 天前434

全部回覆(2)我來回復

  • P粉087074897

    P粉0870748972023-08-28 16:11:51

    如果您想使用,它可以讓您存取歷史對象,允許您透過history.push('/my-path')更改頁面 code>直接來自js的方法。您將面臨這樣的問題:BrowserRouter 沒有可用的 history 屬性,且 Router 沒有可用的 basename

    解決方法如下:

    const App: React.FC = () => {
      // do not put a slash at the end of the basename value.
      const history = createBrowserHistory({ basename: '/your-base-name' });
    
      return <Router history={history}>
               ...
             </Router>;
    }
    

    https://reacttraining.com/react-router/web/ api/BrowserRouter/basename-string

    回覆
    0
  • P粉647449444

    P粉6474494442023-08-28 00:10:44

    使用最新的react router (v4),你可以輕鬆做到這一點

    <BrowserRouter basename="/calendar">
      <Link to="/today"/> // renders <a href="/calendar/today">
    </BrowserRouter>

    回覆
    0
  • 取消回覆