如何在 React JS 中处理错误的路由 404 响应并路由到默认根上下文。
我尝试使用<Route path='*' component={Home} />
但它不起作用,并且路径不正确,给出 404。
最佳答案
我认为你应该提供更多信息。到目前为止您得到的答案做出了您未指定的假设。我想知道什么在为index.html提供服务,以及404是什么意思。服务器是否给了你这个?你们的路线不匹配吗?你使用什么版本的 react 路由器? webpack 开发服务器和/或开发中间件是否混合在一起?
我假设后者在这里发挥作用,但如果您指定更多内容后需要,我会更改我的答案..
如果您使用 webpack-dev-server,请确保以下内容位于您的配置文件中
devServer: {
historyApiFallback: true, <- falls back to index.html if path is not routed
publicPath: '/', <- where the bundle is
}
确保在 webpack 配置中您的输出具有 publicPath
output: {
path: path.sesolve(__dirname, 'dist') <- absolute path where the bundle is
publicPath: '/' <- makes sure HtmlWebpackPlugin injects '/' before bundle.js in output index.html
}
如果您不使用 HtmlWebpackPlugin,请确保您的 index.html 引用“/bundle.js”而不仅仅是 bundle 。
如果您在节点中使用 Webpack-dev-middleware 来提供索引和 bundle ,请注意它是从内存中提供的,而不是任何/build 或/dist 目录。
如果问题出在react-router上,我不明白404问题。您的意思是它与您的任何路线都不匹配?如果您使用react-router v4,请确保您拥有最新的测试版,最新版(4.0.0-beta.6)和之前的版本之间存在一些变化,可能会破坏您期望的功能。
在路由器 v4 中使用它来捕获不匹配的路由:
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/someroute" component={SomeComponent}/>
<Route component={NoMatchedRouteComponent}/> <- Catches "404" and redirects
</Switch>
也许您的组件中的 console.log(this.props.match)
可以查看您的路由发生了什么。
希望这对您有所帮助,请提供更多详细信息,以便我们更好地帮助您..
关于reactjs - 如何处理react中的404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42548482/