【发布时间】: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 不,不一样。谢谢
-
如果你像我上面那样添加一个默认值?