【问题标题】:React-router can't redirect to "/" routeReact-router 无法重定向到“/”路由
【发布时间】:2021-07-24 17:55:16
【问题描述】:

我无法通过react-router 重定向到“/”路径。我的App.jsx 文件如下所示:

ReactDOM.render(<Router>
    <Switch>
      <Route exact path="/" component={Content} />
      <Route path="/login" component={Auth} />
      {/* <Route component={NotFound} /> */}
    </Switch>
  </Router>, document.getElementById("root"));

添加 这是我的身份验证组件,它决定了重定向登录或注册的身份验证表单:

export default class Auth extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoginActive: true,
    };

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

  formChange() {
    this.setState({ isLoginActive: !this.state.isLoginActive });
  }

  render() {
    const { isLoginActive } = this.state;

    let view = isLoginActive ? (
      <Login apiUrl={apiUrl} formChange={this.formChange} history={this.props.history} />
    ) : (
      <Register apiUrl={apiUrl} formChange={this.formChange} history={this.props.history} />
    );

    return (
      <div className="container">
        {getCookie("token") == null ? view : <Redirect to="/" />}
      </div>
    );
  }
}

这里是登录组件,在成功的 axios 请求上重定向到链接到内容组件的“/”路径

    export default class Login extends React.Component {
      //constructor
    
      login() {
        // axios request
        this.setState({ userLoggedIn: true });
      }
    
      render() {
        return this.state.userLoggedIn ? (
          <Redirect exact to="/" />
        ) : (
          <div className="base-container">
              <button type="button" className="btn" onClick={this.login}>
                Login
              </button>
            </div>
          </div>
        );
      }
    }

如果我在这里将&lt;Redirect exact to="/" /&gt; 的路线更改为任何其他路线,例如'/home',一切都会完美运行。所以我不能重定向到'/'路由。

【问题讨论】:

    标签: reactjs redirect react-router


    【解决方案1】:

    您是否尝试过像这样向&lt;Redirect/&gt; 添加“from”和“to”属性:

    <Redirect exact from="/login" to="/" />
    

    根据React Router docs,您必须将“exact”与“from”属性一起使用。请注意下方。

    精确:布尔 完全匹配;等同于 Route.exact。注意:这只能与 from 结合使用,以在渲染 a 的内部时精确匹配位置。详情请参阅。

    我通常也使用“history”属性进行重定向,该属性作为props,由react-router-dom提供,在像这样的路由器组件中。 "It Pushes a new entry onto the history stack"。它是这样工作的 - this.props.history.push('/')

    编辑 ----------

    你的导入是像 "import {BrowserRouter as Router} from 'react-router-dom" 吗? 我在这里复制了您的代码,并且工作正常。我如上所述导入。在 Auth 组件中,我正在传递所有路由器道具,而不仅仅是历史,使用 &lt;Redirect /&gt; 或将“/”路由放在历史堆栈顶部,看看:

    Index.js:

    ReactDOM.render(
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Content} />
          <Route path="/login" component={Auth} />
        </Switch>
      </BrowserRouter>,
      document.getElementById('root')
    )
    

    Auth.js

    export default class Auth extends React.Component {
      constructor(props) {
        super(props)
    
        this.state = {
          isLoginActive: true,
        }
      }
    
      render() {
        // passing all route props (location, history, match)
        const view = <Login {...this.props} />
    
        return <div className="container">{view}</div>
      }
    }
    

    登录.js

    export default class Login extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          userLoggedIn: false,
        }
        this.login = this.login.bind(this)
      }
    
      login() {
        this.setState({ ...this.state, userLoggedIn: true })
      }
    
      render() {
        // console.log(this.props)
        return this.state.userLoggedIn ? (
          //   <Redirect exact from="/login" to="/" /> also works
          this.props.history.push('/')
        ) : (
          <div className="base-container">
            <button type="button" className="btn" onClick={this.login}>
              Login
            </button>
          </div>
        )
      }
    }
    

    另请注意,在登录组件中带有 className "base-container" 的 div 中有一个不正确的额外 &lt;/div&gt;

    【讨论】:

    • 我试过你的方法,但没有奏效。我尝试将add this.props.history.push('/') 输入到我的登录方法中,但什么也没发生(我将历史记录从我的 Auth 组件转移到了登录道具中)。可能问题出在我的中间身份验证组件中?
    • 或者它可能与我在 React 应用程序中使用的 ASP 连接?
    • 而且 history.push 也适用于任何路线,而不是 '/' 路径
    • 我编辑了答案,是的,我认为问题出在中间 Auth 组件中,在传递道具时。当您传递 Route 道具时,我建议您按照答案(传递所有道具)而不仅仅是一个或另一个,因为它在 react-router-dom 文档中是如何显示的,例如当您使用“render”属性时,而不是“组件”来传递道具。
    【解决方案2】:

    问题恰好出在作为中间层的 Auth 组件中。删除后一切正常。 Felipe Curcio 非常感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 2020-12-31
      • 2016-12-19
      相关资源
      最近更新 更多