Javascript 带React路由器v4的嵌套路由-解决方案
我正在尝试让嵌套路由在React路由器v4上工作。我指的是这一页 那么他们是如何做嵌套路由的呢Javascript 带React路由器v4的嵌套路由-解决方案,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我正在尝试让嵌套路由在React路由器v4上工作。我指的是这一页 那么他们是如何做嵌套路由的呢 import React from 'react' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' const BasicExample = () => ( <Router> <div> <ul> &
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
export default BasicExample
指向webpack.config.js,当服务器没有响应时,它将始终指向index.html
这是我的推荐信。阅读它可能很有用这通常是服务器问题,而不是客户端代码中的任何问题。如果将express与静态服务一起使用:
app.use(express.static('build'));
然后,如果目录build
中没有文件,或者另一个express route(例如/about
)中没有匹配的文件,则express不会做出任何响应
除了上面的静态中间件之外,您还需要添加一个catch-all-route来表示——但在您的路由定义中,它必须在它之后
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../build', 'index.html'));
};
这是一个通配符路由,因此静态中间件未匹配的任何内容都将发送index.html。一旦这些信息进入浏览器,react路由器将接管并加载正确的组件。但这是节点。。。我正在使用react并用webpack构建它。所以它应该还能用,不是吗?示例代码在没有expression的情况下工作如果您收到错误
无法获取/about
,则您的服务器正在运行,正在查找与/about
匹配的(服务器端)路由处理程序,但未找到。这是您键入URL时的预期行为。不,即使我使用服务器将所有内容路由到index.html,它仍然不起作用。它的路径没有定义。请参考这里@DaurenAkilbekov,非常感谢。我花了一整天的时间试图解决这个问题,但你帮了我!
devServer: {
port: 3000,
historyApiFallback: {
index:'index.html'
}
}
app.use(express.static('build'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../build', 'index.html'));
};