【问题标题】:React redirect on error avoiding code duplication对错误做出反应重定向,避免代码重复
【发布时间】:2021-03-18 23:30:13
【问题描述】:

我有一个 graphql 函数,它检查请求令牌是否已过期,如果已过期,我需要它重定向到登录。在我的应用程序的每个页面上,我都会调用服务器以获取一些数据,如果出现错误,我需要重定向到登录。我需要消除这里的代码重用,我需要一些帮助。

const client = new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, operation, forward }) => {
      if (graphQLErrors) {
        graphQLErrors.forEach(err => {
          // handle errors differently based on its error code
          switch (err.extensions.code) {
            case 'INTERNAL_SERVER_ERROR':
              // This is the case when the user session expires
              if (err.path && err.path[0] === 'updateToken') {
                removeItem(AUTH_TOKEN);
                history.push('/login');
              }
              return forward(operation);
            default:
              return forward(operation);
          }
        });
      }
    }),
  ]),  
});

在我的应用程序的每个页面上,我都会向 graphql 客户端发出请求,

const Profiles = () => {
  // Omitted code
  const { loading, error, data, refetch, fetchMore } = useQuery(
    GET_PROFILES(),
    {
      variables: { id },
    }
  );

  if (loading) {
    return <Loading />;
  }

  if (error) {
    // I need to find a way to eliminate this line because I am duplicating it on every page of my app
    if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
      return <Redirect to="/login" />;
    }

    return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
  }

  return (
    <div>OMITTED</div>
  );
};

在我的应用程序的每个页面上,if 语句都有相同的错误。我需要删除检查错误消息的行,因为我在我的应用程序的每个页面上都复制了它。我在想也许我可以在 case 'INTERNAL_SERVER_ERROR': 案例上做点什么。

如果这些错误是真的,我不想显示警报

【问题讨论】:

标签: reactjs graphql


【解决方案1】:

使用高阶组件:

const WithQuery = (Comp, query, getVariables) => (props) => {
  const { loading, error, data, refetch, fetchMore } = useQuery(
    query(),
    {
      variables: getVariables(),
    }
  )

  if (loading) {
    return <Loading />;
  }

  if (error) {
    // I need to find a way to eliminate this line because I am duplicating it on every page of my app
    if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
      return <Redirect to="/login" />;
    }

    return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
  }

  return <Comp {...props} data={data} />
}

const Profiles = WithQuery(({ data, name }) => {
  return (
    <div>OMITTED</div>
  );
}, GET_PROFILES, () => ({ id }));

// usage
<Profiles name="Test Name" />

【讨论】:

  • 这就是我要找的!如何访问配置文件组件中的数据变量?
  • 您还知道我在哪里可以找到有关如何使用 graphql 执行此操作的更多信息吗?
  • 我已经编辑了代码,以便您能够访问数据变量
  • 你能不能也展示一下如何将 props 传递给 Profiles 组件?
  • const Profiles = ({ names }) = WithQuery(({ data }) =&gt; { 似乎不起作用
猜你喜欢
  • 2014-03-07
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多