React Router v6 – createBrowserRouter 无法获取错误

huangapple go评论69阅读模式
英文:

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 &quot;/&quot;), but it seems not working. Can anyone help pointing out what could be missing?

React Router v6 – createBrowserRouter 无法获取错误

Here is how index.js looks like:

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import App from &#39;./app&#39;;
import { createBrowserRouter, RouterProvider } from &#39;react-router-dom&#39;;

const router = createBrowserRouter([
  {
    path: &quot;/&quot;, // This is working
    element: &lt;App /&gt;,
  },
  {
    path: &quot;/hello&quot;, // This get &quot;Cannot GET /hello&quot; error 
    element: &lt;div&gt;Hello&lt;/div&gt;
  }
])

ReactDOM.createRoot(document.getElementById(&#39;root&#39;))
  .render(
    &lt;React.StrictMode&gt;
      &lt;App /&gt;
    &lt;/React.StrictMode&gt;
  )

webpack common config:

const path = require(&#39;path&#39;);

const babelLoaderRule = {
  test: /\.(js|jsx)$/,
  exclude: /(node_modules|bower_components)/,
  use: {
    loader: &#39;babel-loader&#39;,
    options: {
      presets: [&#39;@babel/preset-env&#39;, &#39;@babel/preset-react&#39;],
      plugins: [
        &#39;@babel/plugin-transform-runtime&#39;,
        &#39;@babel/plugin-proposal-class-properties&#39;,
      ]
    }
  }
}

const urlLoaderRule =  {
  test: /\.(png|jpe?g|gif)$/i,
  loader: &#39;url-loader&#39;,
  options: {
    name: &#39;[name].[ext]&#39;,
    outputPath: &#39;images&#39;,
    limit: 8192,
  }
}

module.exports = {
  entry: {
    app: &#39;./src/index.js&#39;,
  },
  output: {
    filename: &#39;js/[name]-bundle-[chunkhash:6].js&#39;,
    path: path.resolve(__dirname, &#39;../dist&#39;),
  },
  module: {
    rules: [babelLoaderRule, urlLoaderRule]
  }
};

webpack dev config:

const path = require(&#39;path&#39;);
const { merge } = require(&#39;webpack-merge&#39;);
const common = require(&#39;./webpack.common.config.js&#39;);
const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);
const webpack = require(&#39;webpack&#39;);

module.exports = merge(common, {
  mode: &#39;development&#39;,
  devtool: &#39;eval-cheap-module-source-map&#39;,
  devServer: {
    static: path.join(__dirname, &#39;../dist&#39;),
    port: 3000,
    compress: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: &#39;public/index.html&#39;,
      inject: &#39;body&#39;,
      hash: false,
    }),
    new webpack.DefinePlugin({
      &#39;process.env.NODE_ENV&#39;: JSON.stringify(process.env.NODE_ENV || &#39;development&#39;)
    }),
  ],
  module: {
    rules: [{        
        test: /\.css$/,
        use: [
            &#39;style-loader&#39;,
            &#39;css-loader&#39;,
            &#39;postcss-loader&#39;,
        ]
    }]
  }
});

serve the app by:

&quot;start&quot;: &quot;webpack serve --open --config ./config/webpack.dev.config.js&quot;,

答案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.

&lt;React.StrictMode&gt;
  &lt;App /&gt;
&lt;/React.StrictMode&gt;

Should be

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import App from &#39;./app&#39;;
import { createBrowserRouter, RouterProvider } from &#39;react-router-dom&#39;;

const router = createBrowserRouter([
  {
    path: &quot;/&quot;,
    element: &lt;App /&gt;,
  },
  {
    path: &quot;/hello&quot;,
    element: &lt;div&gt;Hello&lt;/div&gt;
  }
]);

ReactDOM.createRoot(document.getElementById(&#39;root&#39;))
  .render(
    &lt;React.StrictMode&gt;
      &lt;RouterProvider router={router} /&gt;
    &lt;/React.StrictMode&gt;
  );

The dev webpack configuration should also specify historyApiFallback: true in the devServer property.

const path = require(&#39;path&#39;);
const { merge } = require(&#39;webpack-merge&#39;);
const common = require(&#39;./webpack.common.config.js&#39;);
const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);
const webpack = require(&#39;webpack&#39;);

module.exports = merge(common, {
  mode: &#39;development&#39;,
  devtool: &#39;eval-cheap-module-source-map&#39;,
  devServer: {
    historyApiFallback: true, // &lt;--
    static: path.join(__dirname, &#39;../dist&#39;),
    port: 3000,
    compress: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: &#39;public/index.html&#39;,
      inject: &#39;body&#39;,
      hash: false,
    }),
    new webpack.DefinePlugin({
      &#39;process.env.NODE_ENV&#39;: JSON.stringify(process.env.NODE_ENV || &#39;development&#39;)
    }),
  ],
  module: {
    rules: [{        
        test: /\.css$/,
        use: [
            &#39;style-loader&#39;,
            &#39;css-loader&#39;,
            &#39;postcss-loader&#39;,
        ]
    }]
  }
});

答案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 &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import App from &#39;./app&#39;;
import { createBrowserRouter, Switch, Route } from &#39;react-router-dom&#39;;
const router = createBrowserRouter({
routes: [
{
path: &#39;/&#39;,
element: &lt;App /&gt;,
},
{
path: &#39;/hello&#39;,
element: &lt;div&gt;Hello&lt;/div&gt;,
},
],
});
ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(
&lt;React.StrictMode&gt;
&lt;Switch&gt;{router}&lt;/Switch&gt;
&lt;/React.StrictMode&gt;
);

huangapple
  • 本文由 发表于 2023年3月4日 05:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定