且构网

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

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

更新时间:2023-01-22 15:39:10

您必须配置Web服务器,以便为您定义的所有路由,或在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服务器通常不会注意到这些事情。他们知道如何提供网址。而且,当您请求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>