gpt4 book ai didi

reactjs - React 不路由到 "/"以外的路由

转载 作者:行者123 更新时间:2023-12-02 03:41:28 25 4
gpt4 key购买 nike

我无法在“/”之外的任何路由上渲染任何组件。这是我的routes.js 代码

 import React from 'react'
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
} from 'react-router-dom'
import StockTable from './containers/stockTableContainer';
import StockDetail from './containers/stockDetailContainer';

export const getRoutes = (store) => {
return(
<Router>
<div>
<Route exact path ='/' component ={StockTable}/>
<Route path ='/details' component ={StockDetail}/>
</div>
</Router>
)
}

我可以在“/”路由上渲染 StockDetail 组件,但无法在“/details”上路由它。

我也尝试过使用但仍然无法渲染“/details”

完整代码:https://github.com/shrutis18/stockApp

最佳答案

If your application is hosted on a static file server, you need to use a <HashRouter> instead of a <BrowserRouter>.

这是因为您的服务器不知道如何处理对 / 以外的路径发出的请求。对于BrowserRouter要工作,任何可路由的请求都应该由 index.html 提供服务.

摘自 FAQ

When you load the root page of a website hosted on a static file server (e.g., http://www.example.com), a <BrowserHistory> might appear to work. However, this is only because when the browser makes the request for the root page, the server responds with the root index.html file.

If you load the application through the root page, in-app navigation will work because requests are not actually made to the server. This means that if you load http://www.example.com and click a link to http://www.example.com/other-page/, your application will match and render the /other-page/ route.

However, you will end up with a blank screen if you were to refresh a non-root page (or just attempt to navigate directly to it). Opening up your browser's developer tools, you will see an error message in the console informing you that the page could not be loaded. This is because static file servers rely on the requested file actually existing.

进一步推进

This is not an issue when your server can respond to dynamic requests. In that situation, you can instruct the server to catch all requests and serve up the same index.html file.

关于reactjs - React 不路由到 "/"以外的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48476992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com