从React-router传递params到Apollo Client 2.1中的查询组件

时间:2018-04-11 02:56:33

标签: javascript graphql react-router-v4 react-apollo apollo-client

如何将Route中的match.params传递给新的Apollo查询组件? 我正在尝试在Apollo 2.1之前构建一个React组件并使用新的查询组件来学习如何使用它们。

之前的代码:

const Post = ({ data: { loading, error, post } }) => {
  if (error) return <h1>Error fetching the post!</h1>
  if (!loading) {
    return (
      <article>
        <h1>{post.title}</h1>
        <div className='Post-placeholder'>
          <img
            alt={post.title}
            src={`https://media.graphcms.com/resize=w:650,h:366,fit:crop/${post.coverImage.handle}`}
          />
        </div>
        <Markdown
          source={post.content}
          escapeHtml={false}
        />
      </article>
    )
  }
  return <h2>Loading post...</h2>
}

export const singlePost = gql`
  query singlePost($slug: String!) {
    post: Post(slug: $slug) {
      id slug title
      coverImage { handle }
      content dateAndTime
    } }`

export default graphql(singlePost, {
  options: ({ match }) => ({
    variables: {
      slug: match.params.slug
    }
  })
})(Post)

这是新代码:

const Post = (slug) => (
  <Query query={singlePost} variables={{slug: slug.match.params.slug}}>
    {({ loading, error, post }) => { 
      if (loading || !post) return <h2>Loading post...</h2>
      if (error) return <h1>Error fetching the post!</h1>
      return (
        <article>
        <h1>{post.title}</h1>
        <div className='Post-placeholder'>
          <img
            alt={post.title}
            src={`https://media.graphcms.com/resize=w:650,h:366,fit:crop/${post.coverImage.handle}`}
          />
        </div>
        <Markdown
          source={post.content}
          escapeHtml={false}
        />
      </article>
      )
    }}
  </Query>
)

export const singlePost = gql`
      query singlePost($slug: String!) {
        post: Post(slug: $slug) {
          id slug title
          coverImage { handle }
          content dateAndTime
        } }`

export default Post;

我console.log post得到一个空对象,我是console.log slug.match.params.slug我得到了React-router传递的帖子的slug。在控制台中也没有错误,我得到加载屏幕然后是黑页。此外,Apollo Dev工具会在缓存中显示查询中的数据。

1 个答案:

答案 0 :(得分:1)

我认为它应该是(long)left*(long)right,而不是渲染回调中的data

post