简体   繁体   English

React-router 无法重定向到“/”路由

[英]React-router can't redirect to "/" route

I cannot redirect to "/" path via react-router .我无法通过react-router重定向到“/”路径。 My App.jsx file looks like:我的App.jsx文件如下所示:

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

ADDED Here is my Auth component which decides what auth form to redirect Login or Register:添加这是我的身份验证组件,它决定了重定向登录或注册的身份验证表单:

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>
    );
  }
}

And here is Login component that on successful axios request redirects to "/" path that linked to Content component这是登录组件,成功的 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>
        );
      }
    }

If I change route here <Redirect exact to="/" /> to any other, eg'/home' everything works perfectly.如果我将此处的路线<Redirect exact to="/" />更改为任何其他路线,例如'/home',一切都会完美运行。 So I just can't redirect to '/' route.所以我不能重定向到'/'路线。

Have you tried add "from" and "to" attributes to <Redirect/> like this:您是否尝试过像这样向<Redirect/>添加“from”和“to”属性:

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

According to React Router docs you have to use "exact" together with "from" attribute.根据React Router 文档,您必须将“exact”与“from”属性一起使用。 Notice below.注意下方。

exact: bool Match from exactly;精确:布尔匹配从精确; equivalent to Route.exact.Note: This can only be used in conjunction with from to exactly match a location when rendering a inside of a.等价于 Route.exact。注意:这只能与 from 结合使用,以在渲染 a 的内部时精确匹配位置。 See for more details.有关更多详细信息,请参阅。

I also usually make redirects using the "history" property, that comes as props, provided by react-router-dom, in router components like this one.我通常也使用“历史”属性进行重定向,该属性作为 props 提供,由 react-router-dom 提供,在像这样的路由器组件中。 "It Pushes a new entry onto the history stack" . “它将新条目推入历史堆栈” It works like this - this.props.history.push('/')它是这样工作的 - this.props.history.push('/')

EDIT ----------编辑 - - - - -

Is your import like "import {BrowserRouter as Router} from 'react-router-dom"?您的导入是否像“从'react-router-dom”导入{BrowserRouter as Router}? I have replicate your code here, and works fine.我在这里复制了您的代码,并且工作正常。 I imported as mentioned above.我如上所述导入。 And in Auth Component I'm passing all router props, not just history, works using <Redirect /> or putting the '/' route on top of the history stack, take a look:在 Auth 组件中,我传递了所有路由器道具,而不仅仅是历史,使用<Redirect />或将“/”路由放在历史堆栈顶部,看看:

Index.js:索引.js:

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

Auth.js 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>
  }
}

Login.js登录.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>
    )
  }
}

Note also that you have an incorrect extra </div> inside the div with className "base-container" in Login Component另请注意,在登录组件中带有 className "base-container" 的 div 中有一个不正确的额外</div>

The problem was exactly in Auth component as an intermediate layer.问题正是在 Auth 组件中作为中间层。 After removing it everything worked fine.删除后一切正常。 Felipe Curcio thanks a lot for you help. Felipe Curcio非常感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM