且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React 路由在 facebook 的 create-react-app 构建中不起作用

更新时间:2023-01-22 15:00:07

你必须配置你的网络服务器来为你定义的所有路由提供相同的页面,或者在 React 中实现服务器端渲染.开发网络服务器可能是这样配置的,但生产服务器(Apache?Nginx?别的什么?)不是.这个问题可能会有所帮助.

You must configure your webserver to serve the same page for all the routes you've defined, or implement server-side rendering in React. The development webserver is probably configured as such, but the production one (Apache? Nginx? something else?) isn't. This question might help.

这是因为 React 用于构建单页应用程序.您有一个传统网页,它加载一些脚本——最有可能是构建过程的输出,然后这些脚本处理其他所有事情.这包括生成新的 DOM,向服务器"发出数据请求,甚至在视图更改时通过操纵 URL 来伪造多页应用程序行为.最后一点是 react-router 所做的.

The reason why this is, is that React is used in building single page applications. You have a single traditional webpage, which loads some scripts - the output of your build process most likely, and then those scripts take care of everything else. This includes generating new DOM, making requests to the "server" for data, and even faking a multi-page app behaviour by manipulating the URL when views change. This last bit is what react-router does.

然而,Web 服务器通常不会注意到这些事情.他们知道如何提供 URL.当您请求 yourdomain.com/时,他们将提供该主页,但是当您请求 yourdomain.com/some/page/123 时,除非经过特殊配置,否则他们将不知道要提供什么.一种配置是还为这些其他 URL 返回主页的内容.React-router 将获取 URL 并使用适当的组件,所以一切都会正常>

However, web servers are usually oblivious to these things. They know how to serve URLs. And when you request yourdomain.com/ they'll serve that main page, but when you request yourdomain.com/some/page/123 they won't know what to serve, unless specially configured. And one configuration is to also return the contents of the main page for these other URLs. React-router will pick up the URL and use the proper components, so everything will look OK>