【发布时间】:2019-06-27 17:43:06
【问题描述】:
我在 Javascript 中执行了一个查询来获取我的应用程序中当前用户的数据。此查询返回当前用户(客户端)的数据,这些数据用于使用 Apollo 客户端和 GraphQL 检查客户端对我的 React 应用程序中各个页面的访问权限。
但是,对于只有管理员才能访问的页面,在进行此查询时,页面会呈现,以便没有管理员权限的用户可以临时查看页面的内容。一旦检查了权限并且知道用户没有访问权限,就会产生一个错误页面。
我希望立即生成此错误页面,以便没有权限的客户根本无法查看任何内容。
// This is a currentUser.js file that is imported by various React components
// which uses the query to check permissions
import gql from 'graphql-tag';
export default apolloClient => apolloClient
.query({
query: gql`
query CURRENT_USER {
name
age
gender
permissions
}
`,
})
.then(({ data }) => ({ currentUser: data }))
.catch(() =>
({ currentUser: {} }));
// This is a AdministratorPage.jsx file that shouldn't render whilst
// permissions are checked
import currentUser from '../lib/currentUser';
import React, { Component } from 'react';
import { ApolloConsumer } from 'react-apollo';
class AdministratorPage extends Component {
render() {
return (
<ApolloConsumer>
{(client) => {
currentUser(client).then((data) => { ...}
有什么想法吗?
【问题讨论】:
-
我通常解决这个问题的任何合并方法是在渲染之前进行检查,这也允许我利用
spinners/loading status bars。虽然,我通常将我的主要状态保持在可能的最高组件(直到可能发生不必要的重新渲染之前)。三元运算符或 JSX 条件{true && (render)}可以帮助您。我希望这是有道理的。
标签: javascript reactjs graphql apollo