首页 > 解决方案 > React-router 无法重定向到“/”路由

问题描述

我无法通过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>
        );
      }
    }

如果我将此处的路线更改<Redirect exact to="/" />为任何其他路线,例如'/home',一切都会完美运行。所以我不能重定向到'/'路线。

标签: reactjsredirectreact-router

解决方案


您是否尝试过添加“from”和“to”属性,<Redirect/>如下所示:

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

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

精确:布尔匹配从精确;等同于 Route.exact。注意:这只能与 from 结合使用,以在渲染 a 的内部时精确匹配位置。有关更多详细信息,请参阅。

我通常也使用“历史”属性进行重定向,该属性作为 props 提供,由 react-router-dom 提供,在像这样的路由器组件中。“它将新条目推入历史堆栈”。它是这样工作的 -this.props.history.push('/')

编辑 - - - - -

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

索引.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>
    )
  }
}

另请注意,</div>在登录组件中,您的 div 中有一个不正确的额外内容,其中 className 为“base-container”


推荐阅读