使用 typescript、react 和 graphql 以正确方式进行查询的问题

     2023-03-10     190

关键词:

【中文标题】使用 typescript、react 和 graphql 以正确方式进行查询的问题【英文标题】:Problem with make query in correct way using typescript, react and graphql 【发布时间】:2021-01-26 05:18:13 【问题描述】:

请原谅我这个可能很愚蠢的问题,但这是我使用 graphql 并做出反应的第一步。我尝试创建内部是 GraphQL 查询和传入道具的组件。 Props 是一个应该传递给 GraphQL 查询的查询。我知道我做错了什么,但我不知道是什么。我将带有 apollo 提供程序的客户端之类的所有内容添加到我的应用程序组件结构中。 在主页(index.js)上,我的布局很简单:

import Layout from "../components/layout"
import SearchForm from "../components/searchForm"

export default function Home() 
  return  (
    <Layout pageTitle="React App" headerTitle="Search repositories on Github">
      <SearchForm repositoryNameDefaultValue='' />
    </Layout>
  );

然后我有一个名为 searchForm 的组件:

import  Component, ChangeEvent  from "react";
import Input from "./input";
import Button from "./button";
import style from "./searchForm.module.scss";
import FindRepositoryResults from "./test";

interface IMyComponentErrors 
  repositoryNameError: string;


interface IMyComponentProps 
  repositoryNameDefaultValue: string;


interface IMyComponentState 
  repositoryName: string;
  formIsSend: boolean;
  errors: IMyComponentErrors;


const validateForm = (errors: IMyComponentErrors): boolean => 
  let valid = true;
  Object.values(errors).forEach((val) => val.length > 0 && (valid = false));
  return valid;
;

const validRepositoryNameRegex = RegExp(/^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/i);

export default class SignUpFormContainer extends Component<
  IMyComponentProps,
  IMyComponentState
> 
  constructor(props: IMyComponentProps) 
    super(props);
    this.state = 
      repositoryName: this.props.repositoryNameDefaultValue,
      formIsSend: false,
      errors: 
        repositoryNameError: "",
      
    ;

    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleClearForm = this.handleClearForm.bind(this);
    this.handleChangeRepositoryName = this.handleChangeRepositoryName.bind(this);
  

  handleChangeRepositoryName(event: ChangeEvent<HTMLInputElement>): void 
    event.preventDefault();
    const  value  = event.target;
    let errors = this.state.errors;

    if (!validRepositoryNameRegex.test(value)) 
      errors.repositoryNameError = "Invalid repository name";
     else if (!value) 
      errors.repositoryNameError = "Repository name is required";
     else 
      errors.repositoryNameError = "";
    

    this.setState( errors, repositoryName: value );
  

  handleClearForm() 
    this.setState(
      repositoryName: "",
      formIsSend: false
    );
  

  handleFormSubmit(event) 
    event.preventDefault();
    const  repositoryName  = this.state;
    let errors = this.state.errors;

    if (!repositoryName) 
      errors.repositoryNameError = "Repository name is required";
    

    this.setState( errors );

    if (!validateForm(this.state.errors)) 
      return;
     else 
      this.setState( formIsSend: true );
    
  

  render() 
    const  errors  = this.state;

    return (
      <div>
       !this.state.formIsSend ? (
      <form
        aria-label="Search repositories by name"
        autoComplete="off"
        onSubmit=this.handleFormSubmit
        className = style.formSearchRepository
      >
        <Input
          type="text"
          title="Repository name:"
          name="repositoryName"
          placeholder="Enter name of repository"
          value=this.state.repositoryName
          error=errors.repositoryNameError.length > 0
          errorMessage=errors.repositoryNameError
          onChange=this.handleChangeRepositoryName
          required
        />
        <Button
          onClick=this.handleFormSubmit
          title="Search repository in Github by name"
          children="Search"
        />
      </form>
      ) : <FindRepositoryResults repositoryName=this.state.repositoryName/>
      </div>
    );
  

最后一个更成问题的查询在哪里:

import React from "react";
import  gql, useQuery  from "@apollo/client";

const SEARCH_REPOSITORY = gql`
query findRepositories($query: String!) 
    search(first: 10, query: $query, type: REPOSITORY) 
        nodes 
          ... on Repository 
            name,
            owner 
              login
            
            primaryLanguage 
              name
            ,
            stargazers 
              totalCount
            ,
            stargazerCount,
            languages(first: 20, orderBy: field: SIZE, direction: ASC ) 
              totalCount
              nodes 
                name
              
            ,
            issues 
              totalCount
            
            shortDescriptionHTML,
            updatedAt,
            watchers 
              totalCount
            
          
        
    

`;

interface IFindRepositoryComponentProps 
  repositoryName: string;


interface IFindRepositoryComponentState 
  detailsAreOpen: boolean;


interface RepositoryData 
  data: any;


interface RepositoryVars 
  query: string;


export default class FindRepositoryResults extends React.Component<IFindRepositoryComponentProps, IFindRepositoryComponentState> 
  constructor(props: IFindRepositoryComponentProps) 
    super(props);
    this.state =  detailsAreOpen: false ;

    this.showDetails = this.showDetails.bind(this);
  

  showDetails() 
    this.setState(state => (
      detailsAreOpen: !state.detailsAreOpen
    ));
  

  render() 
    const  loading, data, error  = useQuery<any, RepositoryVars>(
      SEARCH_REPOSITORY ,
       variables:  query: this.props.repositoryName  
    );

    return (
      <section>
        <h3>Results</h3>
        loading ? (
          <p>Loading ...</p>
        ) : error ? (<p>Error error</p>) : (
          <div>
             data.search.nodes.length == 0 ? (<p>No results found.</p>) : data && data.search.nodes.map((repo) => (
              <div>
                <p>Name: repo.name</p>
                <p>Owner: repo.owner.login</p>
                <p>Number of stars (total): repo.stargazerCount</p>
                <p>Primary language: repo.primaryLanguage.name</p>
          
                <button onClick=this.showDetails>this.state.detailsAreOpen ? 'Show less' : 'Show more'</button>
                <div>
                  Details:
                  repo.issues.totalCount
                  repo.languages.totalCount
                  repo.shortDescriptionHTML
                  repo.stargazers.totalCount
                  repo.updatedAt
                  repo.watchers.totalCount
                </div>
              </div>
            ))
          </div>
        )
      </section>
    );
     

在上面的这个组件中,我进行了查询,但没有得到结果。我不确定,但版本不匹配(DOM 渲染),我在与 typescript、react 和 apollo 一起正确执行此操作时遇到问题。如果有人能告诉我正确的方法和例子,我会很高兴。谢谢

【问题讨论】:

【参考方案1】:

我没有使用 typescript,但使用了 React hooks 和 GraphQL。因此,您进行了查询,但没有得到任何结果?如果执行查询,则应该有结果或错误。如果它走得那么远,它可能有助于下载 Apollo-Graphql 插件(也许是谷歌浏览器?)。

例如,我会在 graphi-ql 游乐场中尝试查询。

此外,查询中的变量名查询有点混乱。

最好的,J

【讨论】:

React 和 TypeScript:避免使用上下文默认值

】React和TypeScript:避免使用上下文默认值【英文标题】:React&TypeScript:Avoidcontextdefaultvalue【发布时间】:2020-08-0314:07:47【问题描述】:为了更好地学习React、TypeScript和Context/Hooks,我正在制作一个简单的Todo应用程序。但是,使... 查看详情

如何使用 usestate 和 setstate 而不是 this.setState 使用 react 和 typescript?

】如何使用usestate和setstate而不是this.setState使用react和typescript?【英文标题】:Howtouseusestateandsetstateinsteadofthis.setStateusingreactandtypescript?【发布时间】:2020-09-1618:38:06【问题描述】:我想使用react和typescript实现一个DragAndDrop组件,... 查看详情

使用 React、Typescript 和 Webpack 显示静态图像

】使用React、Typescript和Webpack显示静态图像【英文标题】:DisplayingastaticimageusingReact,TypescriptandWebpack【发布时间】:2017-11-0221:01:15【问题描述】:我正在尝试使用webpack和webpack-dev-server在React组件中显示图像作为项目的一部分。到目... 查看详情

绝对导入:React 和 Typescript

】绝对导入:React和Typescript【英文标题】:AbsoluteImports:ReactandTypescript【发布时间】:2020-07-2809:16:29【问题描述】:背景我有一个使用create-react-app和typescript引导的React应用程序。随着应用程序的增长,(目标)我想实现绝对导入... 查看详情

Typescript 和 React:使用解构的事件处理程序的正确类型是啥?

】Typescript和React:使用解构的事件处理程序的正确类型是啥?【英文标题】:TypescriptandReact:Whatisthepropertypeforaneventhandlerthatusesdestructuring?Typescript和React:使用解构的事件处理程序的正确类型是什么?【发布时间】:2021-07-1214:02:38... 查看详情

如果使用 react 和 typescript 找不到 id 会返回啥?

】如果使用react和typescript找不到id会返回啥?【英文标题】:Whattoreturnifnoidfoundusingreactandtypescript?如果使用react和typescript找不到id会返回什么?【发布时间】:2021-05-1222:56:20【问题描述】:我有一个查询“详细信息”,如下所示que... 查看详情

如何使用 Typescript、React 和 Webpack 导入 SCSS 或 CSS 模块

】如何使用Typescript、React和Webpack导入SCSS或CSS模块【英文标题】:HowtoimportSCSSorCSSmoduleswithTypescript,ReactandWebpack【发布时间】:2019-10-0115:20:03【问题描述】:我想在我的项目中使用.scss(使用react和typescript构建),所以我使用typings-... 查看详情

Typescript 和 React:使用 React.Component 和条件类型化道具时类型推断失败

】Typescript和React:使用React.Component和条件类型化道具时类型推断失败【英文标题】:TypescriptandReact:FailingtypeinferencewhenusingReact.Componentandconditionaltypedprops【发布时间】:2019-06-2116:22:21【问题描述】:在下面的设置中,我尝试为onChan... 查看详情

React-intl,使用 api 和 Typescript

】React-intl,使用api和Typescript【英文标题】:React-intl,useapiwithTypescript【发布时间】:2017-04-0815:56:15【问题描述】:我想使用react-intlAPI的formatMessage函数插入一条消息作为占位符,但我不知道访问该函数的正确方法。这是我所拥有... 查看详情

如何修复已使用 react 和 typescript 声明的错误标识符?

】如何修复已使用react和typescript声明的错误标识符?【英文标题】:HowtofixtheerrorIdentifierhasalreadybeendeclaredusingreactandtypescript?【发布时间】:2021-02-0312:47:09【问题描述】:我想使用react修复错误“标识符配置已被声明”?我在文件L... 查看详情

使用 React、Typescript 和 ES6 进行 Jest 测试

】使用React、Typescript和ES6进行Jest测试【英文标题】:JesttestingwithReact,TypescriptandES6【发布时间】:2017-02-2511:05:19【问题描述】:我在使用ES6编写的Jest(v16.0.1)测试用Typescript(v2.0.3)编写的React组件时遇到了一些问题。我正在使用ts-jest... 查看详情

我想在 Laravel 项目中使用 TypeScript 和 React

】我想在Laravel项目中使用TypeScript和React【英文标题】:IwouldliketouseTypeScriptandReactinLaravelProject【发布时间】:2020-05-2307:51:53【问题描述】:我想在Laravel项目中使用打字稿并做出反应。但是,当我执行“nomrundev”时发生了错误。我... 查看详情

如何将 CSS 模块与 Typescript、React 和 Webpack 一起使用?

】如何将CSS模块与Typescript、React和Webpack一起使用?【英文标题】:HowcanyouuseCSSmodulestogetherwithTypescript,ReactandWebpack?【发布时间】:2021-03-0811:42:14【问题描述】:我只是在React上构建一个可重用的组件,因此我没有使用react-create-app... 查看详情

使用 Typescript 和 React.Konva 指定 onClick 事件类型

】使用Typescript和React.Konva指定onClick事件类型【英文标题】:SpecifyingonClickeventtypewithTypescriptandReact.Konva【发布时间】:2017-12-1818:45:24【问题描述】:我正在尝试摆脱我的tslint错误Typedeclarationof\'any\'losestype-safety.,但我正在努力弄清... 查看详情

使用 airbnb 和 prettier 扩展的 ESLint 配置,用于使用 typescript、jest 和 react-hooks 的 react 项目

】使用airbnb和prettier扩展的ESLint配置,用于使用typescript、jest和react-hooks的react项目【英文标题】:ESLintconfigextendedwithairbnbandprettier,forareactprojectusingtypescript,jestandreact-hooks【发布时间】:2019-11-0219:33:48【问题描述】:我很困惑如何... 查看详情

如何使用 Typescript 和 useState 将类型对象设置为 React 的初始值?

】如何使用Typescript和useState将类型对象设置为React的初始值?【英文标题】:HowtosetatypeobjectasinitialvalueofReactusingTypescriptanduseState?【发布时间】:2021-11-0319:23:55【问题描述】:我刚开始学习使用Typescript构建React应用程序,我真的被... 查看详情

在 React 和 Typescript 中使用 .env 文件读取 URL 环境变量的问题

】在React和Typescript中使用.env文件读取URL环境变量的问题【英文标题】:ProblemwithreadingURLenvironmentvariablewith.envfileinReactandTypescript【发布时间】:2022-01-1703:16:57【问题描述】:我是react-typescript的新手,我在src文件夹中创建了名为proc... 查看详情

如何在 React 和 TypeScript 项目中使用 types.d.ts 文件

】如何在React和TypeScript项目中使用types.d.ts文件【英文标题】:Howusingtypes.d.tsfileinReact&TypeScriptproject【发布时间】:2020-08-1706:15:08【问题描述】:我有React和TypeScript项目。这是我在某些组件中的文件夹结构,例如:-ComponentFolder-... 查看详情