【发布时间】:2018-08-19 21:47:54
【问题描述】:
我正在使用 react-router v4 编写身份验证代码,并且我正在使用带有渲染道具的 PrivateRoute,如文档:Redirects (Auth)
我要做的是:每当用户导航到一条路线时,我想调度一个操作以向后端发出请求以验证他是否已登录。
像这样:
// App.js
class App extends Component {
checkAuth = () => {
const { dispatch, } = this.props;
// callback to dispatch
}
render() {
const props = this.props;
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/" component={Login} />
<PrivateRoute
exact
path="/dashboard"
component={Dashboard}
checkIsLoggedIn={this.checkAuth}
/>
{/* ... other private routes here */}
</Switch>
</div>
</Router>
);
}
在 PrivateRoute.js 中,我正在监听路由以检查它是否更改,但是当路由更改时,此函数被调用太多次,这是调度操作以发出请求的问题。
// PrivateRoute.js
const PrivateRoute = ({ component: Component, auth, checkIsLoggedIn, ...rest }) => (
<Route
{...rest}
render={props => {
props.history.listen((location, action) => {
if (checkIsLoggedIn) {
// Here I check if the route changed, but it render too many times to make a request
checkIsLoggedIn(); // here is the callback props
}
});
if (auth.login.isLoggedIn) {
return <Component {...props} />;
} else {
return <Redirect to={{ pathname: "/login", state: { from: props.location } }} />
}
}
}
/>
);
我需要帮助找出一个在路由发生变化时调用后端的好方法。
【问题讨论】:
-
您可以在我们的Dashboard组件的
componentDidMount方法中向您的后端发出请求 -
@ArnoldGandarrilas 但我想在用户导航的每条私人路线中发出请求
-
PrivateRoute是一个自定义的 React 组件。它与react-router无关。将其更改为有状态类,并在其componentDidMount方法中添加您的身份验证调用。 -
@FisNaN 我应该将其更改为使用渲染道具或 HoC 的类吗?
-
临时检查是否有烫发是个好方法
标签: javascript reactjs react-router react-router-v4