React,Graphql,Typescript-对象可能为“ null”。 TS2531

时间:2019-11-30 11:06:13

标签: reactjs typescript graphql

我正在使用Graphql和Typescript开发React应用。

我正在使用Apollo Generate从Graphql模式创建类型

一切似乎都可以正常进行,我可以进行控制台记录数据。

我的问题是显示数据,但出现错误

Object is possibly 'null'.  TS2531

schema.js

exports.typeDefs = `

  type Recipe{
    _id: ID!
    name: String!
    description: String
  }

  type Query{
    recipe: [Recipe]
  }

  type Mutation{
    addRecipe(name: String, description: String): Recipe
  }

`   

queries / index.tsx

import { gql } from 'apollo-boost';

export const GET_ALL_RECIPES = gql`
  query RecipeData{
    recipe{
      _id
      name
      description
    }
  }
`   

Generated / RecipeData.ts

export interface RecipeData_recipe {
  __typename: "Recipe";
  _id: string;
  name: string;
  description: string;
}

export interface RecipeData {
  recipe: (RecipeData_recipe | null)[];
}

App.tsx

import React from 'react';
import './App.css';

import { useQuery } from 'react-apollo-hooks';
import { GET_ALL_RECIPES } from '../queries';
import { RecipeData } from '../generated/RecipeData';


const App: React.FC = () => {

  const { data, loading } = useQuery<RecipeData>(GET_ALL_RECIPES, {
    suspend: false
  })

  if (loading || !data) return <div>Loading</div>

  console.log(data)

  return (
    <ul>
      {data && data.recipe.map((recipe) =>
        <li key={recipe._id}>{recipe.name}</li>
      )}
    </ul>
  );
}

export default App;

我在这里收到配方错误

<li key={recipe._id}>{recipe.name}</li>

引用graphql模式以在React应用程序中使用它的正确方法是什么。

0 个答案:

没有答案