我有一个名为App的顶级组件:
render(
<BrowserRouter basename="/">
<App/>
</BrowserRouter>
, document.getElementById('main'));
其中有一个名为MainView的组件:
export default class App extends React.Component {
render() {
return (
<div>
<MainMenu />
<div className="md-drawer-relative">
<MainView />
</div>
</div>
);
}
}
MainView设置到某些组件的路由:
export default class MainView extends React.Component {
render() {
return (
<div>
<Switch>
<Route path='/settings' component={Settings} />
<Route path='/communications' component={Communications} />
<Route path='/diagnosis' component={Diagnosis} />
</Switch>
</div>
);
}
}
我可以通过在浏览器中输入URL来访问这些组件。现在,我想在这些组件之一中设置更多路由,因此我在设置中设置了一些路由:
export default class Settings extends React.Component {
render() {
return (
<div>
<Switch>
<Route exact path='/settings/general' component={SettingsGeneral} />
<Route exact path='/settings/network' component={SettingsNetwork} />
</Switch>
</div>
);
}
}
当我现在想访问此URL(localhost:8080/settings/general
或localhost:8080/settings/network
)时,我得到一个404。
我在这里做错了什么?我当然已经检查了所有组件是否存在并且可以定位,并且导入了相应的库。
我正在使用webpack-dev-server --mode development
-----编辑----
const SettingsComponent = () => {
console.log('Subcomponent loaded!');
return <h1>This is a subcomponent</h1>;
};
export default class Settings extends React.Component {
render() {
console.log(this.props.location);
return (
<div>
<Switch>
<Route path='/settings/:settings_component' exact component={SettingsComponent} />
</Switch>
</div>
);
}
}
访问上述URL时,我也收到404。
答案 0 :(得分:1)
我认为您的问题与webpack-dev-server的配置有关。尝试更改
publicPath: '/'
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'
})
]
};
该示例摘自本文:https://tylermcginnis.com/react-router-cannot-get-url-refresh/
答案 1 :(得分:0)
不确定为什么它不起作用。但是,您可以尝试使用Path Params吗?像这样:
<Route exact path='/settings' component={Settings}/>
<Route path='/settings/:category' component={SettingCategories}/>