【问题标题】:Redirection Issue in React JS ComponentReact JS 组件中的重定向问题
【发布时间】:2017-11-22 15:28:36
【问题描述】:

我正在尝试通过组件文件中的条件语句重定向到其他组件。

myfile.js 的片段

import { Redirect } from 'react-router-dom';
render(){
        if (isLoggedIn()) {
            return(
                <Redirect to='/Myaccount' />
            );
        }   
    } 

当条件为真时,它会改变浏览器的 url 但内容没有加载。
请让我知道我做错了什么。

【问题讨论】:

  • 检查这个答案,我想这会回答你的问题stackoverflow.com/questions/44434041/…
  • 相同,重定向......浏览器中的网址已更改,但页面内容未加载......
  • 你用了withRouter了吗,还有没有报错或者你有匹配的路由
  • 是的,我使用“withRouter”作为..>>>>import { withRouter } from 'react-router-dom'; >>>>>>componentDidMount() { if (isLoggedIn()) { this.props.history.push('/Myaccount'); } }>>>>>>export default connect(mapStateToProps, mapDispatchToProps) (withRouter(Login));....... ......................而且我在控制台中没有收到任何错误
  • 试试这个import { withRouter } from 'react-router';

标签: reactjs redirect conditional jsx


【解决方案1】:

使用history.push 可能会更好,如下所示。

if (isLoggedIn()) {
   return(
       this.props.history.push("/Myaccount");
   );
}   

【讨论】:

  • 你不会返回它,你也不会在渲染函数中拥有它
  • @Drum > this.props.history.push("/Myaccount"); >>> 我试过了,但还是不行....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 2023-01-25
  • 2019-06-28
  • 2023-03-21
  • 2021-11-12
  • 2019-12-17
  • 2011-02-07
相关资源
最近更新 更多