我正在使用带有 thunk 的 react router v4 在我的应用程序中进行路由。我想阻止<AccountPage />
向未登录的用户呈现组件。我在服务器上使用 id 和令牌发送获取请求以检查数据库是否用户有此令牌。如果它有 - 渲染<AccountPage />
,如果没有 - 重定向回家。
我不明白什么是实现“条件路由”的好方法,我发现了一些似乎几乎完全适合我的任务的东西。
https://gist.github.com/kud/6b722de9238496663031dbacd0412e9d
但问题是condition
in<RouterIf />
总是未定义的,因为 fetch 的异步性。我尝试以异步方式处理此问题,但没有任何结果或出现错误:
Objects are not valid as a React child (found: [object Promise]) ...
或者
RouteIf(...): Nothing was returned from render. ...
这是代码:
//RootComponent
<BrowserRouter>
<Switch>
<Route exact path='/' component={HomePage}/>
<Route path='/terms' component={TermsAndConditionsPage}/>
<Route path='/transaction(\d{13}?)' component={TransactionPage}/>
<RouteIf
condition={( () => {
if( store.getState().userReducer.id, store.getState().userReducer.token) {
// Here i sending id and token on server
// to check in database do user with this id
// has this token
fetch(CHECK_TOKEN_API_URL, {
method: 'post',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
id: store.getState().userReducer.id,
token: store.getState().userReducer.token
})
})
.then res => {
// If true – <RouteIf /> will render <AccountPage />,
// else - <Redirect to="/">
// But <RouteIf /> mounts without await of this return
// You can see RouteIf file below
if(res.ok) return true
else return false
})
}
})()}
privateRoute={true}
path="/account"
component={AccountPage}
/>
</Switch>
</BrowserRouter>
//RouteIf.js
const RouteIf = ({ condition, privateRoute, path, component }) => {
// The problem is that condition is
// always undefined, because of fetch's asyncronosly
// How to make it wait untill
// <RouteIf condition={...} /> return result?
return condition
? (<PrivateRoute path={path} component={component} />)
:(<Redirect to="/" />)
}
export default RouteIf
如何condition
等待直到fetch
返回答案?或者也许有另一种更好的方法来检查用户是否登录?