不确定这里发生了什么。我已经设置了我的路由,当我转到我的第一个页面localhost:8080 /第一个路由按预期呈现。但是如果我在localhost中输入url:8080 / store预期路由失败,我收到404无法找到(甚至没有回到我未找到的组件)。
但是,如果我设置了一个链接并单击该链接,它将按预期呈现我的商店路线。
不管是/store
渲染我的StorePicker组件,无论它是输入到URL还是通过链接到元素选择,都不应该这样做?
App.js
import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
//Components
import StorePicker from './components/StorePicker.js';
import Main from './components/Main';
import NotFound from './components/NotFound';
const Routes = () => {
return (
<Router>
<div>
<Link to="/store">Store</Link>
<Switch>
<Route path="/" exact component={StorePicker} />
<Route path="/store" component={Main} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
)
}
render(<Routes />, document.querySelector('#container'));
答案 0 :(得分:0)
假设您正在使用Webpack。如果是这样,在webpack配置中添加一些内容应该可以解决问题。具体而言,output.publicPath = '/'
和devServer.historyApiFallback = true
。
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};