簡體   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