【发布时间】:2020-03-27 19:11:18
【问题描述】:
用例
我想在用户尝试访问私人路线时拨打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 routing and private routes Question 并检查了Authenticate async with react-router-v4 question,但两个答案都对我不起作用。
如果我尝试在渲染中解决承诺,则会显示以下错误:
我怎样才能实现这个用例?
【问题讨论】:
-
尝试使用 HOC 可能
-
你的项目中没有使用 redux 吗?
-
@AyushGupta 什么是 HOC?
-
@m.sohail 不,我只使用 React。没用过redux
-
高阶组件
标签: reactjs react-router