【问题标题】:React-Router's Redirect throws a webpack error when i use itReact-Router 的重定向在我使用时会引发 webpack 错误
【发布时间】:2019-06-30 07:22:02
【问题描述】:

所以我正在编写一个 React 应用程序,基本上我正在尝试使用 react-router-dom 包从一条路径重定向到另一条路径。但是,每当我的路径与 Redirect 元素的 'from' 属性匹配时,我都会收到 webpack 错误。这是我的代码:

import React, { Component } from "react";
import "./App.sass";
import HeaderComponent from "./HeaderComponent";
import BodyComponent from "./BodyComponent";
import {
    BrowserRouter as Router,
    Route,
    Switch,
    Link,
    Redirect
} from "react-router-dom";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            increment: 0
        };

        this.parallax = this.parallax.bind(this);
    }

    componentDidMount() {
        window.addEventListener("scroll", this.parallax);
    }

    componentWillUnmount() {
        window.removeEventListener("scroll", this.parallax);
    }

    parallax() {
        if (
            document.documentElement.scrollTop <
            document.getElementById("hero").clientHeight
        ) {
            let scrollTop = document.documentElement.scrollTop,
                offset = Math.floor(scrollTop / 3);
            this.setState({ increment: offset }, () =>
                console.log(this.state.increment)
            );
        }
    }

    render() {
        return (
            <Router>
                <div>
                    <HeaderComponent
                        increment={this.state.increment}
                        days={this.state.days}
                    />
                    <Switch>
                        <Redirect from="/calabar" to="/tokyo" />
                        <Route
                            path="/:city"
                            render={props => <BodyComponent {...props} />}
                        />
                    </Switch>
                </div>
            </Router>
        );
    }
}

export default App;

这是我得到的错误截图:

编辑

当 url 设置为与重定向的“from”属性不匹配的另一个路径时,它可以正常工作,如下面的屏幕截图所示:

请帮助我做错了什么?或者可能是安装错误?还是 react-router-dom 本身的错误?

【问题讨论】:

  • 能发下 react-router-dom 和 webpack 的版本吗?
  • @Sreeram react-router-dom的版本是5.0.1,webpack的版本是4.29.6
  • 同样的设置对我有用。所以问题必须来自其他地方。它在没有重定向的情况下工作吗?
  • 是的。在 url 与 Redirect 元素的“from”属性匹配之前,它可以完美运行。在屏幕截图中,当 url 设置为“/calabar”时会引发错误。如果将其设置为其他任何内容,则可以轻松使用。
  • 尝试清除缓存?隐身模式等?

标签: reactjs webpack react-router


【解决方案1】:

显然,重定向在我的 Switch 中不起作用。原因,到现在我也想不通。在放弃了几个星期的 React-Router 并回来尝试重定向而不将它嵌套在 Switch 中之后它工作了。所以实现我想要的另一种方法是:

<Redirect from="/calabar" to="/tokyo" />
/**Longer list of Redirects**/
<Switch>
   <Route
      path="/:city"
      render={props => <BodyComponent {...props} />}
   />
   /**Extra Routes whose path only match the to attribute of the Redirects**/
</Switch>

虽然在 API 文档中,他们在 Switch 中嵌套了重定向,但我不知道为什么当 尝试它时它会吐出错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2021-04-25
    • 2017-09-14
    • 2019-03-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多