【问题标题】:which way of fetching data from Graphql server is better?从 Graphql 服务器获取数据的哪种方式更好?
【发布时间】:2018-06-04 21:28:46
【问题描述】:

我有一个使用 React 作为客户端框架和 Graphql 来运行 API 的应用程序。 计划正在获取用户帖子和帖子计数。

客户端

const Profile = () => (
 <div>
  <PostCount />
  <Posts />
 </div>  
)

const PostCount = () => ...

const Posts = () => ...

我们需要在 Posts 组件中显示帖子,在 Count 组件中显示帖子数。 所以我的问题是,哪个更好。

在一个请求中获取 Profile 组件中的所有数据,并将其作为 props 发送到 Post 和 Count 组件。或获取 Count 组件中的帖子计数和 Post 组件中的帖子。

场景一包括对服务器的一个请求和更大的数据块。

场景二包括两个对服务器的请求和较小的数据块。

场景一服务器端:

const schema = `
 type Query {
  feeds(): Feed!
}

type Feed {
 posts: [Post!]!
 count: Int!
}

type Post {
 ...
}
`


async function feed() {
 const posts: await Post.findAll();
 const count = await Post.count();


 return {
  count
  posts,
 }
}

场景二服务器端:

const schema = `
 type Query {
  posts(): [Post!]!
  count(): Int!
 }

 type Post {
  ...
 }
`

async function feed() {
 const posts: await Post.findAll();
 return posts;
}

async function count() {
 const count = await Post.count();
 return count;
}

附:还要考虑更大的数据。帖子和计数是示例。例如用户帖子和用户 cmets。

【问题讨论】:

    标签: javascript reactjs graphql


    【解决方案1】:

    两种方法都是正确的!选择更好的方法取决于您的应用程序!

    count 通常比获取数据更快(有人可能会搞砸!:D),所以如果您单独获取它,您可以在帖子仍在加载时更快地显示它。

    顺便说一句,GQL 自己处理Promise!所以不需要异步等待!

    【讨论】:

    • 我知道两者都是正确的。但是哪种方法具有更好的性能?关于异步等待。我从我的代码中复制了 sn-ps。原来的解析器有更多的功能。忘记删除 asyinc await。
    • 单独调用它们具有更好的性能,因为您可以更快地获得可用的数据!
    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2011-01-02
    • 1970-01-01
    • 2017-06-08
    • 2016-11-24
    相关资源
    最近更新 更多