英文:
React Router v6 - createBrowserRouter Can not get error
问题
我尝试使用createBrowserRouter
来创建一个新的路由(除了根路径"/"
之外),但似乎没有起作用。是否有人可以帮忙指出可能缺少什么?
以下是index.js
的代码示例:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
{
path: "/", // 这个可以正常工作
element: <App />,
},
{
path: "/hello", // 这里会报错 "Cannot GET /hello"
element: <div>Hello</div>
}
])
ReactDOM.createRoot(document.getElementById('root'))
.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
Webpack通用配置(webpack common config):
const path = require('path');
const babelLoaderRule = {
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
'@babel/plugin-transform-runtime',
'@babel/plugin-proposal-class-properties',
]
}
}
}
const urlLoaderRule = {
test: /\.(png|jpe?g|gif)$/i,
loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'images',
limit: 8192,
}
}
module.exports = {
entry: {
app: './src/index.js',
},
output: {
filename: 'js/[name]-bundle-[chunkhash:6].js',
path: path.resolve(__dirname, '../dist'),
},
module: {
rules: [babelLoaderRule, urlLoaderRule]
}
};
Webpack开发配置(webpack dev config):
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.config.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = merge(common, {
mode: 'development',
devtool: 'eval-cheap-module-source-map',
devServer: {
static: path.join(__dirname, '../dist'),
port: 3000,
compress: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
inject: 'body',
hash: false,
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
],
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
]
}]
}
});
启动应用程序的命令:
"start": "webpack serve --open --config ./config/webpack.dev.config.js",
英文:
I tried to use createBrowserRouter
to create a new route (apart from the root "/"
), but it seems not working. Can anyone help pointing out what could be missing?
Here is how index.js looks like:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
{
path: "/", // This is working
element: <App />,
},
{
path: "/hello", // This get "Cannot GET /hello" error
element: <div>Hello</div>
}
])
ReactDOM.createRoot(document.getElementById('root'))
.render(
<React.StrictMode>
<App />
</React.StrictMode>
)
webpack common config:
const path = require('path');
const babelLoaderRule = {
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
'@babel/plugin-transform-runtime',
'@babel/plugin-proposal-class-properties',
]
}
}
}
const urlLoaderRule = {
test: /\.(png|jpe?g|gif)$/i,
loader: 'url-loader',
options: {
name: '[name].[ext]',
outputPath: 'images',
limit: 8192,
}
}
module.exports = {
entry: {
app: './src/index.js',
},
output: {
filename: 'js/[name]-bundle-[chunkhash:6].js',
path: path.resolve(__dirname, '../dist'),
},
module: {
rules: [babelLoaderRule, urlLoaderRule]
}
};
webpack dev config:
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.config.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = merge(common, {
mode: 'development',
devtool: 'eval-cheap-module-source-map',
devServer: {
static: path.join(__dirname, '../dist'),
port: 3000,
compress: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
inject: 'body',
hash: false,
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
],
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
]
}]
}
});
serve the app by:
"start": "webpack serve --open --config ./config/webpack.dev.config.js",
答案1
得分: 2
以下是翻译的内容:
原文:
It appears you are missing actually rendering the router (and routes). Right now the app is only rendering the App
component.
翻译:
看起来您实际上没有渲染路由器(以及路由)。目前应用程序仅渲染App
组件。
原文:
Should be
翻译:
应该是
原文:
The dev webpack configuration should also specify historyApiFallback: true
in the devServer
property.
翻译:
开发阶段的Webpack配置还应在devServer
属性中指定historyApiFallback: true
。
英文:
It appears you are missing actually rendering the router (and routes). Right now the app is only rendering the App
component.
<React.StrictMode>
<App />
</React.StrictMode>
Should be
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
{
path: "/",
element: <App />,
},
{
path: "/hello",
element: <div>Hello</div>
}
]);
ReactDOM.createRoot(document.getElementById('root'))
.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
The dev webpack configuration should also specify historyApiFallback: true
in the devServer
property.
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.config.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = merge(common, {
mode: 'development',
devtool: 'eval-cheap-module-source-map',
devServer: {
historyApiFallback: true, // <--
static: path.join(__dirname, '../dist'),
port: 3000,
compress: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
inject: 'body',
hash: false,
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
],
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
]
}]
}
});
答案2
得分: 0
尝试运行此代码,查看是否解决了问题。
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app';
import { createBrowserRouter, Switch, Route } from 'react-router-dom';
const router = createBrowserRouter({
routes: [
{
path: '/',
element: <App />,
},
{
path: '/hello',
element: <div>Hello</div>,
},
],
});
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Switch>{router}</Switch>
</React.StrictMode>
);
英文:
Try this code to see whether it is resolved.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app';
import { createBrowserRouter, Switch, Route } from 'react-router-dom';
const router = createBrowserRouter({
routes: [
{
path: '/',
element: <App />,
},
{
path: '/hello',
element: <div>Hello</div>,
},
],
});
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Switch>{router}</Switch>
</React.StrictMode>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论