首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用React的应用程序中,路由不按预期工作-路由器v6

在使用React的应用程序中,路由不按预期工作-路由器v6
EN

Stack Overflow用户
提问于 2022-09-20 22:27:44
回答 1查看 250关注 0票数 1

我用的是反应路由器v6。我遵循教程https://reactrouter.com/en/main/start/tutorial#the-root-route并按指定的方式添加了我的路由。但有些奇怪的事情发生了,我不知道为什么会这样。

我已经按照使用createBrowserRouter方法指定的方式创建了路由器。

代码语言:javascript
复制
const router = createBrowserRouter([
      {
        path: '/',
        element: <RootPage />,
        errorElement: <ErrorPage />,
      },
      {
        path: 'hi',
        element: <ErrorPage />,
        // errorElement: <ErrorPage />,
      },
    ]);

在我的app.js文件中,我有以下内容:

代码语言:javascript
复制
<RouterProvider router={router} />

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

代码语言:javascript
复制
Cannot GET /hi

但是,如果通过我的RootPage组件中的链接转到这个路由,它就会工作得非常好。顺便说一下,这个链接是来自的link组件.

我的RootPage组件的代码如下:

代码语言:javascript
复制
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,我也应该能够看到组件被呈现,而不是无法获得/hi。任何帮助都将不胜感激。

此外,我已经配置我的webpack手动。运行我的项目的启动脚本如下所示:

代码语言:javascript
复制
"webpack serve --config webpack/webpack.config.js --env env=dev"

我的webpack.config.js文件的内容如下:

代码语言:javascript
复制
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的建议是:

代码语言:javascript
复制
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(),
  ],
};

对于dev:

代码语言:javascript
复制
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配置:

代码语言:javascript
复制
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',
};
EN

回答 1

Stack Overflow用户

发布于 2022-09-20 22:52:59

它似乎修改了我的webpack配置的开发工作。

代码语言:javascript
复制
 devServer: {
    port: 4000,
    hot: true, //enable webpack hot module replacement
    open: true,
    historyApiFallback: true,
  },

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73793239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档