为何react-router可正确处理正则path却同时抛出错误?
Why does React Router's Route throw a PropTypes warning when using a regex path even though path-to-regexp supports it?
Let's break down exactly what's going on here:
Your Use Case & Current Setup
You wanted a component to render on every path except the root (/), so you used a regex^\/.+$directly as thepathprop for yourRoute. This regex correctly matches all paths starting with/followed by at least one character (so it excludes the root), and the functionality works as expected—but React Router throws a PropTypes warning.The Root Cause of the Warning
Even though the underlying library React Router uses for path parsing (path-to-regexp) does support regular expressions as valid inputs, theRoutecomponent's PropTypes validation doesn't align with this capability.The
Routecomponent's PropTypes explicitly define thepathprop as either astringorundefined. When you pass aRegExpobject instead of a string, the PropTypes check fails, triggering the warning you see:Warning: Failed prop type: Invalid prop
pathof typeregexpsupplied toRoute, expectedstring.In short: the path parsing logic accepts regex, but the component's built-in type safety check doesn't allow it.
A Warning-Free Fix
Instead of passing a regex object, use a string-based path that leveragespath-to-regexp's syntax to achieve the same behavior. For excluding the root path and matching all other paths, you can use:<Route exact path="/(.*)" component={() => <div><img src="../../../assets/AndreyBogdanov2.jpg" className="me" /></div>} />This string path gets parsed by
path-to-regexpthe same way your original regex did, but it complies with theRoutecomponent's PropTypes requirement for a string—so no warning is thrown.
内容的提问来源于stack exchange,提问作者JaffParker

