簡體   English   中英

在檢查客戶端權限之前,React中的頁面呈現

[英]Page in React renders before the clients permissions are checked

我在Javascript中執行了一個查詢,以獲取應用程序中當前用戶的數據。 此查詢返回當前用戶(客戶端)數據,該數據用於使用Apollo Client和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) => { ...}

有任何想法嗎?

您應該呈現加載頁面或某種加載指示符,直到獲取當前用戶數據。 render方法中嘗試這樣的事情:

<Query query={GET_CURRENT_USER}>
  {({ data, loading, error }) => {
    if (loading) return <Loading />;
    if (error) return <p>ERROR</p>;

    return (
      <AdministratorPage />
    );
  }}
</Query>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM