繁体   English   中英

使用 react-router v6 在 React 应用程序中路由无法按预期工作

[英]Routing not working as expected in React app using react-router v6

我正在使用 react-router v6。 我按照教程https://reactrouter.com/en/main/start/tutorial#the-root-route并按照指定添加了我的路线。 但是发生了一些奇怪的事情,我不知道为什么会这样。

我使用 createBrowserRouter 方法创建了指定的路由器。

const router = createBrowserRouter([
      {
        path: '/',
        element: <RootPage />,
        errorElement: <ErrorPage />,
      },
      {
        path: 'hi',
        element: <ErrorPage />,
        // errorElement: <ErrorPage />,
      },
    ]);

在我的 app.js 文件中,我有这个:

<RouterProvider router={router} />

但是,如果我在浏览器的地址栏中输入localhost:4000/hi ,我会得到

Cannot GET /hi

但是如果 go 通过我的 RootPage 组件中的链接到这条路线,它工作得非常好。 顺便说一句,这个链接是来自 react-router-dom 的链接组件。

我的 RootPage 组件的代码如下:

import { Link } from 'react-router-dom';

const RootPage = () => {

  return (
    <div>
      Home Page
      <Link to="hi">Go to hi route</Link>
    </div>
  );
};

export default RootPage;

理想情况下,即使我直接输入我的 url 即 http://localhost:4000/hi,我应该能够看到我的组件被渲染,而不是不能 GET /hi。 任何帮助,将不胜感激。

我还手动配置了我的 webpack。 运行我的项目的启动脚本如下:

"webpack serve --config webpack/webpack.config.js --env env=dev"

我的 webpack.config.js 文件的内容是:

const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');

module.exports = envVars => {
  const { env } = envVars; //check the script commands in package.json for env variable
  const envConfig = require(`./webpack.${env}.js`);
  const config = merge(commonConfig, envConfig);
  return config;
};

我对 webpack 的产品配置是:

const webpack = require('webpack');
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  mode: 'production',
  devtool: 'source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env.name': JSON.stringify('DAT UI prod'),
    }),
    new BundleAnalyzerPlugin(),
  ],
};

对于开发:

const webpack = require('webpack');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

module.exports = {
  mode: 'development',
  devtool: 'cheap-module-source-map',
  devServer: {
    port: 4000,
    hot: true, //enable webpack hot module replacement
    open: true,
  },
  plugins: [
    new ReactRefreshWebpackPlugin(),
    new webpack.DefinePlugin({
      'process.env.name': JSON.stringify('DAT UI dev'), //defining a env var 'name' having value 'DAT UI dev'
    }),
  ],
};

常用 webpack 配置:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: path.resolve(__dirname, '..', './src/index.tsx'), // entry point for our app
  resolve: {
    extensions: ['.tsx', '.ts', '.js'], // allows us to leave off extensions while importing
  },
  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader', // use babel-loader for files with ts,tsx,js,jsx excluding node_modules
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'], //The order is important here as we want css-loader to run first
      },
      {
        test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
        type: 'asset/resource', //use this module to resolve these above mentioned files
      },
      {
        test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
        type: 'asset/inline',
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, '..', './build'),
    filename: 'main.[contenthash].js', // instructing webpack that bundled code be placed in main.js inside build folder
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '..', './src/index.html'),
      /* 
      inserts bundle.js inside of index.html, we don't manually need to specify script tag in index.html
      also we might define the output filename as bundle.[contentHash].js i.e a dynamic file name, which changes when our code changes,
      we did so for cache busting i.e prevent browser from caching our code file and not updating when our site updates
      so this plugin will help insert our js file automatically in the index.html for us
       */
    }),
    // new CopyPlugin({
    //   patterns: [{ from: 'source', to: 'dest ', noErrorOnMissing: false }],
    // }),
  ],
  stats: 'errors-only',
};

似乎为开发修改我的 webpack 配置有效。

 devServer: {
    port: 4000,
    hot: true, //enable webpack hot module replacement
    open: true,
    historyApiFallback: true,
  },

但不确定我是否也需要对产品配置进行类似的更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM