【问题标题】:Routing doesn't work in react when typing url in browser在浏览器中输入 url 时路由不起作用
【发布时间】:2018-08-16 20:53:12
【问题描述】:

我在下面的课程中有以下路线:

import { Router, Route } from 'react-router-dom';

class App extends React.Component {
    constructor(props) {
        super(props); 
    }

    render() {
        const { alert } = this.props;

        return (
            <Router history={history}>
                <div>                                  
                    <Route path="/login" component={LoginPage} />
                    <Route path="/administrate" component={AdministratePage} />     
                    <Route exact path='/' component={LoginPage} />   
                </div>
            </Router>
        );
    }
}

对于http://localhost:12345/,登录组件正确显示。

但是,当我在浏览器中输入 http://localhost:12345/loginhttp://localhost:12345/administrate 时,我得到了 404。

在导航器中输入“http://localhost:12345/administrate”会得到 404,但如果我输入:

this.props.history.push('/administrate');

在登录组件的渲染方法中,它正确重定向,显示管理组件。

怎么会?我的 F12 控制台中没有错误。非常感谢。

我的 webpack.config.js:

   module.exports = {
   devServer: {
        historyApiFallback: true
    },
        context: __dirname,
        entry: "./index.js",
        output: {
            path: __dirname + "/dist",
            filename: "bundle.js" // naam van de file die je genereert. die bundle.js include je in je cshtml. Wordt voortdurend geupdate als je programmeert
        },
        resolve: {
            extensions: ['.js', '.jsx']
        },

        watch: true, // dan hoef je niet telkens npm run webpack te draaien, je ziet dan in je cmd 'webpack is watching the files'
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /(node_modules)/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['babel-preset-env', 'babel-preset-react'], // deze heb je met npm geinstalleerd
                            plugins: ["transform-object-rest-spread"] // voor het gebruik van de spread operator
                        }
                    }
                },
                {
                    test: /\.css$/,
                    use: ['style-loader', 'css-loader']
                },
                {             // Werkt niet
                    test: /\.jsx$/, loader: 'babel-loader', exclude: '/node_modules/'
                }
            ]
        }
    };

index.js:

import { store } from './_helpers';
import { App } from './App';

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
); 

历史:

import { History } from './index'; // history 4.6.2
import { getConfirmation } from './DOMUtils';

export interface BrowserHistoryBuildOptions {
  basename?: string;
  forceRefresh?: boolean;
  getUserConfirmation?: typeof getConfirmation;
  keyLength?: number;
}

export default function createBrowserHistory(options?: BrowserHistoryBuildOptions): History;

【问题讨论】:

  • @Chris 我已经做到了 - 运气不好。
  • 您是否使用 create-react-app 引导此应用程序?
  • @ChaimFriedman no.
  • 在这种情况下,我们可能还需要查看您的 webpack 配置和 index.html。如果您自己为 index.html 提供服务(而不是使用 webpack-dev-server),那么看到这一点也会有所帮助
  • 尝试将BrowserRouter导入为Router import { BrowserRouter as Router, Route } from "react-router-dom";

标签: reactjs webpack redux


【解决方案1】:

here 所述,缺少在 index.js 中的 BrowserRouter 下包装您的应用程序。

index.js

 import { store } from './_helpers';
    import { App } from './App';
    import { BrowserRouter } from "react-router-dom";

    render(
        <Provider store={store}>
          <BrowserRouter>
            <App />
          </BrowserRouter>
        </Provider>,
        document.getElementById('root')
    ); 

一个完整的例子应该是这样的。

App.js

import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Login from '../../Components/Login/Login';
import Signup from '../../Components/Signup/Signup';
import classes from './Home.css';
import HomePage from '../HomePage/HomePage';


class Home extends Component {

    render() {
    return (
        <div className={classes.Container}>
          <Switch>
            <Route path="/" exact component={HomePage} />
            <Route path="/login" component={Login} />
            <Route path="/signup" component={Signup} />
          </Switch>
        </div>

    );
  }
}

【讨论】:

  • 我做到了。当我在导航栏中键入 url 时仍然是 404。顺便说一句,你 index.js 是重复的
【解决方案2】:

无论输入什么 URL,您的服务器都需要交付您的应用程序,因为您的应用程序在浏览器中正在操纵该 URL。我们当前的服务器不知道如何处理 URL。

Webpack 开发服务器有一个选项可以启用它。打开 package.json 并添加 --history-api-fallback。

"start": "webpack-dev-server --inline --content-base . --history-api-fallback"

我们还需要将我们的相对路径更改为 index.html 中的绝对路径,因为 URL 将位于深层路径,如果应用程序从深层路径开始,将无法找到文件。

<!-- index.html -->
<!-- index.css -> /index.css -->
<link rel="stylesheet" href="/index.css">

<!-- bundle.js -> /bundle.js -->
<script src="/bundle.js"></script>

Configuring Your Server

你也可以在webpack.config.js中配置Webpack服务器

 devServer: {
    historyApiFallback: true,
    contentBase: './',
    hot: true
  },

尝试使用来自 React Router Dom 的HashRouter

import { HashRouter, Route } from "react-router-dom";



             <HashRouter>                          
                    <Route path="/login" component={LoginPage} />
                    <Route path="/administrate" component={AdministratePage} />     
                    <Route exact path='/' component={LoginPage} />  
             </HashRouter>

【讨论】:

  • module.exports = { devServer: { historyApiFallback: { index: "./index.js" }, },我在 webpack.config.js 中添加了上述行,但仍然是 404。
  • module.exports = { devServer: { historyApiFallback: true }, ... 同样的事情。
  • 嗯,你还在导入 BrowserRouter 作为路由器吗?
  • 不,我试过了,但我切换回路由器,它在我下载的原始样板应用程序中工作。
  • 会的。我认为解决方案在这里:stackoverflow.com/questions/27928372/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2016-05-03
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
相关资源
最近更新 更多