reactjs - 如何在 React 重定向到 Private Route 之前解决 Promise?
问题描述
用例
我想在async()
用户尝试访问私人路线时拨打电话。通常在重定向到私有路由时使用同步方法。
这是我使用过的代码,但不了解如何使用异步方法。
class PrivateRoute extends Component {
constructor(props) {
super(props);
this.state = {
isAdmin: null
};
}
componentDidMount() {
console.log("PrivateRoute");
verifyUser().then(res => {
this.setState({
isAdmin: res
});
});
}
render() {
const { component: Component, ...rest } = this.props;
return (
<Route
{...rest}
render={props =>
this.state.isAdmin === true ? (
<InnerLayout>
<Component {...props} />
</InnerLayout>
) : this.state.isAdmin === null ? (
<div>Loading...</div>
) : (
<Redirect
to={{ pathname: "/Login", state: { from: this.props.location } }}
/>
)
}
/>
);
}
}
export default PrivateRoute;
上面代码的问题是 componentDidMount() 调用一次。我已经检查了React 路由和私有路由问题,还检查了Authenticate async with react-router-v4 问题,但两个答案都对我不起作用。
如果我尝试在渲染中解决承诺,则会显示以下错误:
我怎样才能实现这个用例?
解决方案
您可以使用 withRouter ( https://reacttraining.com/react-router/web/api/withRouter )
class PrivateRoute extends Component {
constructor(props) {
super(props);
this.state = {
isAdmin: null
}
}
componentDidMount() {
console.log('PrivateRoute');
verifyUser().then(res => {
if(!res){
this.props.history.push('/Login')
}else
this.setState({
isAdmin: res
})
});
}
render() {
const { component: Component, ...rest } = this.props;
if(this.state.isAdmin === null) return <div>Loading ...</div>
return <Route {...rest} render={props => <InnerLayout><Component/></InnerLayout>}
}
}
export default withRouter(PrivateRoute);
推荐阅读
- python-3.x - 按行和列将 Pandas Dataframe 的元素重组为新的数据框
- azure - 如何在 ARM 模板中组合复制和奇异属性
- ruby-on-rails - 带有嵌套资源的 Rails 表单的 NoMethodError
- php - 嵌套 For Each 循环中的回滚事务
- python - 使用python将现有文本转换为docx中的heading3格式
- python - SQLAlchemy:具有单表继承的邻接表
- sql - 如何在 SQL Server 中的多个列上应用字符串拆分功能
- ads - Google Ads 脚本和 Cookie
- angular - angular 11 ngmodel 未绑定到选择
- javascript - 如何在点击Highcharts Reactjs中的每一列时添加表格?