首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使在定义了propTypes的情况下,ESLint也会抱怨道具验证

即使在定义了propTypes的情况下,ESLint也会抱怨道具验证
EN

Stack Overflow用户
提问于 2019-10-04 12:20:18
回答 1查看 452关注 0票数 0

看看这个:

代码语言:javascript
复制
/* eslint no-console: 0 */
import { ApolloProvider } from '@apollo/react-hooks';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import fetch from 'isomorphic-unfetch';
import Head from 'next/head';
import { useMemo } from 'react';
import PropTypes from 'prop-types';

let apolloClient = null;

/**
 * Creates and configures the ApolloClient
 * @param  {Object} [initialState={}]
 */
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
const createApolloClient = (initialState = {}) => new ApolloClient({
  ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
  link: new HttpLink({
    uri: process.env.CMS, // Server URL (must be absolute)
    credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
    headers: {
      // Get JWT from Strapi Admin -> Plugins -> Documentation -> Retrieve your jwt token
      authorization: `Bearer ${process.env.STRAPI_TOKEN}`,
    },
    fetch,
  }),
  cache: new InMemoryCache().restore(initialState),
});

/**
 * Always creates a new apollo client on the server
 * Creates or reuses apollo client in the browser.
 * @param  {Object} initialState
 */
const initApolloClient = (initialState) => {
  // Make sure to create a new client for every server-side request so that data
  // isn't shared between connections (which would be bad)
  if (typeof window === 'undefined') {
    return createApolloClient(initialState);
  }

  // Reuse client on the client-side
  if (!apolloClient) {
    apolloClient = createApolloClient(initialState);
  }

  return apolloClient;
};

/**
 * Creates and provides the apolloContext
 * to a next.js PageTree. Use it by wrapping
 * your PageComponent via HOC pattern.
 * @param {Function|Class} PageComponent
 * @param {Object} [config]
 * @param {Boolean} [config.ssr=true]
 */
const withApollo = (PageComponent, { ssr = true } = {}) => {
  const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
    const client = useMemo(
      () => apolloClient || initApolloClient(apolloState),
      [apolloClient, apolloState],
    );
    return (
      <ApolloProvider client={client}>
        <PageComponent {...pageProps} />
      </ApolloProvider>
    );
  };

  // Set the correct displayName in development
  if (process.env.NODE_ENV !== 'production') {
    const displayName = PageComponent.displayName || PageComponent.name || 'Component';

    if (displayName === 'App') {
      console.warn('This withApollo HOC only works with PageComponents.');
    }

    WithApollo.displayName = `withApollo(${displayName})`;
  }

  if (ssr || PageComponent.getInitialProps) {
    WithApollo.getInitialProps = async (ctx) => {
      const { AppTree } = ctx;

      // Initialize ApolloClient, add it to the ctx object so
      // we can use it in `PageComponent.getInitialProp`.
      ctx.apolloClient = initApolloClient();
      const { apolloClient } = ctx;

      // Run wrapped getInitialProps methods
      let pageProps = {};
      if (PageComponent.getInitialProps) {
        pageProps = await PageComponent.getInitialProps(ctx);
      }

      // Only on the server:
      if (typeof window === 'undefined') {
        // When redirecting, the response is finished.
        // No point in continuing to render
        if (ctx.res && ctx.res.finished) {
          return pageProps;
        }

        // Only if ssr is enabled
        if (ssr) {
          try {
            // Run all GraphQL queries
            const { getDataFromTree } = await import('@apollo/react-ssr');
            await getDataFromTree(
              <AppTree
                pageProps={{
                  ...pageProps,
                  apolloClient,
                }}
              />,
            );
          } catch (error) {
            // Prevent Apollo Client GraphQL errors from crashing SSR.
            // Handle them in components via the data.error prop:
            // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
            console.error('Error while running `getDataFromTree`', error);
          }

          // getDataFromTree does not call componentWillUnmount
          // head side effect therefore need to be cleared manually
          Head.rewind();
        }
      }

      // Extract query data from the Apollo store
      const apolloState = apolloClient.cache.extract();

      return {
        ...pageProps,
        apolloState,
      };
    };
  }

  return WithApollo;
};

withApollo.propTypes = {
  apolloClient: PropTypes.string.isRequired,
  apolloState: PropTypes.string.isRequired,
};

export default withApollo;

如您所见,我的代码中有以下几行:

代码语言:javascript
复制
import PropTypes from 'prop-types';

代码语言:javascript
复制
withApollo.propTypes = {
  apolloClient: PropTypes.string.isRequired,
  apolloState: PropTypes.string.isRequired,
};

然而,ESLint无法识别这一点,并抛出了这个linting错误:

代码语言:javascript
复制
  2:1   error  Run autofix to sort these imports!                     simple-import-sort/sort
  61:25  error  'apolloClient' is already declared in the upper scope  no-shadow
  61:25  error  'apolloClient' is missing in props validation          react/prop-types
  61:39  error  'apolloState' is missing in props validation           react/prop-types
  91:15  error  'apolloClient' is already declared in the upper scope  no-shadow

为什么?当我清楚地确认了apolloClientapolloState不存在的时候,为什么它说在属性验证中缺少它们呢?我知道我可以用/* eslint react/prop-types: 0 */来抑制它,但我不想这么做。我只想知道我在这里错过了什么。

EN

回答 1

Stack Overflow用户

发布于 2020-07-10 00:16:49

你需要在WithApollo.propTypes上使用proptypes (注意大写"W")。WithApollo的作用域是 withApollo中的

在这里命名有点愚蠢,但无可否认,没有太多更好的选择。这是避免像这样的基于大小写的命名差异的原因之一。

你可能会发现你的proptypes是不正确的。我非常确定apolloClient是一个函数,而apolloState是一个对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58229854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档