【问题标题】:React Redirect if this.props.location.state is null如果 this.props.location.state 为空,则反应重定向
【发布时间】:2021-03-16 00:22:07
【问题描述】:

我使用来自this.props.location.state 的数据设置了一个组件状态。如果它为空,我该如何重定向。

我的应用程序有 2 条路线:

<BrowserRouter>
    <Switch>
       <Route path="/comp2" component={Comp2} />
       <Route path="/" exact component={Comp1} />
    </Switch>
</BrowserRouter>

我可以从 Comp1 转到 Comp2。

<Link to={{ pathname: "/comp2", state: {values} }}>{values.description}</Link>

然后,我用这些数据在 Comp2 中设置我的状态:

constructor(props) {
    super(props);
    this.state = {
        data: this.props.location.state.values
    };
}

它正在工作。但是,如果在浏览器中,我直接访问 http://localhost:3000/comp2,它​​会失败。如果this.props.location.state.values 为空,如何重定向回 http://localhost:3000?

谢谢

【问题讨论】:

  • 为什么会失败?如果您的状态值不存在,可能会添加一个默认值,例如 data: this.props.location.state.values || []
  • 可能是重复的问题。检查这个stackoverflow.com/questions/48497510/…
  • @MarcCharpentier 因为值未定义
  • @jtabuloc 不,不一样。谢谢
  • 如果你像我上面那样添加一个默认值?

标签: reactjs router


【解决方案1】:

试试这个:

常量数据 = this.props.location.state ? history.location.state.values:''

作为回报(

<>
{data ? 
       <div> //ur comp2 component dom </div>
       : 
       <Redirect to="/homePage" />
}
</>
)

【讨论】:

  • 对不起,我没看懂。我应该在哪里添加这个回报?
  • comp2 组件
  • 什么是重定向?它是从哪里来的?
  • 为此在stackoverflow上提出一个新问题,而不是通过react官方文档提出问题,然后开始编码
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多