如何在React中处理元标记?

时间:2019-06-15 10:14:31

标签: reactjs react-apollo

我试图弄清楚如何以一种可访问的方式将meta标签添加到我的网页中。

我的问题是元标记依赖于完成以下操作的异步操作:

import * as React from 'react'
import { Dialog } from '@material-ui/core';
import { withRouter, RouteComponentProps } from 'react-router';
import gql from 'graphql-tag';
import { useQuery } from 'react-apollo-hooks';
import { SubmissionFocus } from './SubmissionFocus';
import MetaTags from 'react-meta-tags';
import { Submission } from '../../AppContext';

const SUBMISSION = gql`query submission($id: String!) {
    submission(id: $id) {
      url
      id
      title
      comments {
        id
        comment
        replyingCommentId
        username
      }
      tags
      embedVideo {
        type
        url
        width
        height
      }
      preview {
        url
        type
        width
        height
      }
    }
  }
`
const BaseRoutedSubmissionFocus = (props: RouteComponentProps) => {
  const path = props.location.pathname;
  const p = path.split('/').filter((s) => s !== "")
  let submissionId = p[0] == 's' && p[1]
  **const submission = useQuery(SUBMISSION, {
    variables: {
      id: submissionId
    },
    skip: submissionId === false
  })**

  const dismiss = () => {
    props.history.push("/");
  }

  if (p[0] !== 's')
    return <></>

  const sub: Submission | undefined = submission.data!.submission
  return <>
    {sub && <MetaTags>
      <title>Page 1</title>
      <meta name="description" content="Some description." />
      <meta property="og:title" content={sub.title} />
      <meta property="og:image" content={sub.preview.url} />
    </MetaTags>}

    < Dialog onClose={dismiss} open={!!submissionId
    }
      maxWidth="lg"
      fullWidth={true} >
      <div style={{ height: '90vh' }}>
        {!submission.loading && submission.data && <SubmissionFocus allowExpand={false} submission={sub} />}
      </div>
    </Dialog >
  </>
}

export const RoutedSubmissionFocus = withRouter(BaseRoutedSubmissionFocus);

useQuery是一个异步操作,在完成加载之前,我还没有meta标签。

对此有任何想法吗?我在想,是否有一种方法可以延迟对任何HTML的响应发出,直到完成某些操作,我才能摆脱它。

1 个答案:

答案 0 :(得分:-1)

我想您可以使用react-helmet来实现:https://github.com/nfl/react-helmet