我正在使用React-router,当我点击链接按钮时,它工作得很好,但当我刷新我的网页时,它没有加载我想要的东西。

例如,我在localhost/joblist和一切都很好,因为我到达这里按下一个链接。但如果我刷新网页,我会得到:

Cannot GET /joblist

默认情况下,它不是这样工作的。最初我有我的URL localhost/#/和localhost/#/joblist,他们工作得很好。但我不喜欢这种类型的URL,所以试图删除#,我写道:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

这个问题不会发生在localhost/,这个总是返回我想要的。

这个应用程序是单页的,所以/joblist不需要向任何服务器询问任何事情。

我的整个路由器。

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

当前回答

我正在使用Webpack,也遇到了同样的问题。

解决方案:

在你的server.js文件中:

const express = require('express');
const app = express();

app.use(express.static(path.resolve(__dirname, '../dist')));
  app.get('*', function (req, res) {
    res.sendFile(path.resolve(__dirname, '../dist/index.html'));
    // res.end();
  });

为什么我的应用程序刷新后不呈现?

其他回答

Preact路由器Preact解决方案

工作与刷新和直接访问

对于那些通过谷歌发现这一点的人,这里有一个preact-router +哈希历史的演示:

const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
const App = () => (
    <div>
        <AddressBar />

        <Router history={createHashHistory()}>
            <div path="/">
                <p>
                    all paths in preact-router are still /normal/urls.
                    using hash history rewrites them to /#/hash/urls
                </p>
                Example: <a href="/page2">page 2</a>
            </div>
            <div path="/page2">
                <p>Page Two</p>
                <a href="/">back to home</a><br/>
            </div>
        </Router>
    </div>
);

斯菲德尔

假设你有以下Home route定义:

<Route exact path="/" render={routeProps => (
   <Home routeProps={routeProps}/>
)}/>

{/* Optional catch-all router */}
<Route render={routeProps => (
       <div><h4>404 not found</h4></div>
)}/>

在你的Home组件中,你可以在ComponentWillMount事件中拦截请求,

const searchPath = this.props.routeProps.location.search;

if (searchPath){
    this.props.routeProps.history.push("/" + searchPath.replace("?",""));
}
else{
    /*.... originally Home event */
}

现在,不是在URL处调用/joblist,而是请求/?<Home>组件将自动将请求重定向到/joblist(注意路径中有额外的问号)。

我使用React.js + Webpack模式。我在package中添加了——history-api-fallback参数。json文件。此时页面刷新工作正常。

每次我修改代码时,网页都会自动刷新。

"scripts": {
  "start": "rimraf build && cross-env NODE_ENV='development' webpack --mode development && cross-env NODE_ENV=development webpack-dev-server --history-api-fallback",
  ...
}

如果你有一个回退到你的index.html,确保在你的index.html文件中你有这个:

<script>
  System.config({ baseURL: '/' });
</script>

这可能因项目而异。

下面是我发现的一个前端解决方案,不需要修改服务器上的任何内容。

假设你的网站是mysite.com,你有一个到mysite.com/about的React Route。 在index.js中,你可以挂载你的顶级组件,你可以像这样放另一个Router:

ReactDOM.render(
<Router>
    <div>
        <Route exact path="/" component={Home} />
        <Route exact path="/about"
            render={(props) => <Home {...props} refreshRout={"/about"}/>}
        />
    </div>
</Router>,

我假设原始路由器位于虚拟DOM的顶级组件之下。如果你正在使用Django,你还必须在你的。url中捕获url:

urlpatterns = [
       path('about/', views.index),
]

不过,这将取决于您使用的后端。请求mysite/about会让你进入index.js(在那里你挂载顶级组件),在那里你可以使用Route的渲染道具,而不是组件道具,并将'/about'作为道具传递给Home组件,在这个例子中。

在Home中,在componentDidMount()或useEffect()钩子中,执行以下操作:

useEffect() {
   //check that this.props.refreshRoute actually exists before executing the
   //following line
   this.props.history.replace(this.props.refreshRoute);
}

我假设你的Home组件是这样渲染的:

<Router>
   <Route exact path="/" component={SomeComponent} />
   <Route path="/about" component={AboutComponent} />
</Router>

关于如何在路由中向组件传递道具,请参考(将道具传递给React路由器渲染的组件)。