首页 > 解决方案 > 反应路由器4 url​​问题

问题描述

import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { history } from './history';
import Login from './components/Login';
import Home from './components/Home';
import NotFound from './presentation/NotFound';
import MainContent from './components/MainContent';
import Overview from './components/Overview';

export default () => {
    return(
        <Router history ={history}>
            <Switch>
                <Route path="/" component={Login} exact />
                <Home>
                    <Route path="/main" exact component={MainContent} />
                    <Route path="/admin/:id" exact component={Overview} />
                </Home>
                <Route component={ NotFound } />
            </Switch>
        </Router>
    );
}

我的 webpack 配置是

const path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            loader: 'babel-loader',test: /\.js$/,exclude: /node_modules/},
{
            test: /\.s?css$/,
            use: [
                'style-loader',
                'css-loader',
                'sass-loader'
            ]
        }, {
            test: /\.(png|jpg|gif)$/,
            use: [
            'file-loader',
            ],
        },{
            test: /\.svg$/,
            use: ['@svgr/webpack'],
        }, {
            test: /\.ttf$/,
            loader: "file-loader?limit=10000"
        }
        ]
    },
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            __CLIENT__: JSON.stringify(true),
            __DEVELOPMENT__: true,
            __DEVTOOLS__: true
        }),
    ],
    optimization:{}
};

因此,当我登陆/mainie MainContent 组件时,它会呈现一个ViewComponent呈现管理员列表的组件,并且单击列表中的单个元素时,它会提供该元素在/admin/:id路线上的详细视图,该组件运行良好。

但是,如果我直接从地址栏刷新或点击 url,那么最初从中呈现的字体和图像的网络请求localhost:8080/somerandomid.ttf现在会从 localhost:8080/admin/somerandomid.ttf抛出 400 错误请求错误中检索,并且样式会更改。

任何人都可以建议如何纠正这个错误。我正在调用一个函数并在单击列表中的元素时传递 id。

this.props.history.push('/admin/' + id);

ViewComponent就是连接管理列表export default withRouter(ViewComponent);以获取 this.props.history.push。

图片网址也是如此。localhost:8080/otherandomid.png 被替换并尝试从 localhost:8080/admin/otherandomid.png 获取 > 并抛出 400 bad request 错误,不显示图像。

标签: reactjswebpackreact-router-v4

解决方案


您需要设置一个基本 URL。

可以通过以下方式完成HtmlWebpackPlugin

plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
        __CLIENT__: JSON.stringify(true),
        __DEVELOPMENT__: true,
        __DEVTOOLS__: true
    }),
    new webpack.HtmlWebpackPlugin({
        base: '/'
    }),
],

或直接在<head>您的index.html文件中:

<base href="/">

推荐阅读