【问题标题】:How can I pass useQuery variable from component prop?如何从组件道具传递 useQuery 变量?
【发布时间】:2021-11-02 10:54:42
【问题描述】:

我有这个问题:

const GET_ANALYTICS = gql`
  query($courseId: String) {
    getStudentsAnalytics(courseId: $courseId) {
        totalStudents,
        studentsNotStartedCoursesYetPercentage,
        studentsFinishedCoursesPercentage,
        studentsInProgressCoursesPercentage,
        studentsCompletedQuizzesPercentage,
        studentsFailedQuizzesPercentage,
        studentsInProgressQuizzesPercentage
    }
}
`

并且在代码中我试图从组件 prop 传递变量:

const AnalyticsStatistic = (courseId: string) => {

  const { loading, error, data } = useQuery(GET_ANALYTICS){
   variables: {courseId},
 }

对于红色带下划线的参数 courseId 出现以下错误:'courseId' 已声明,但其值从未读取。ts(6133) 重复标识符 'courseId'.ts(2300)

对于内部变量:{courseId} 出现这些错误:重复标识符 'courseId'.ts(2300) 绑定元素“courseId”隐式具有“任何”类型。ts(7031)

for inside courseId

for outside courseId

problems in console

【问题讨论】:

  • 添加您的 GET_ANALYTICS 查询代码。并仅尝试 courseId 而不是对象
  • 我已经通过假设查询GET_ANALYTICS 来发布答案,如果这解决了您的问题,请将其标记为已回答
  • courseId 设为字符串,因为查询期望它只是一个字符串
  • 如果有效,请点赞并将其标记为已回答:)
  • 我需要声誉,但我检查它解决了

标签: javascript reactjs graphql frontend apollo


【解决方案1】:

您的GET_ANALYTICS 查询是这样的,因此您不必在对象内传递 courseId 检查下面的代码

const GET_ANALYTICS = gql`
  query($courseId: String) {
    getStudentsAnalytics(courseId: $courseId) {
        ....
    }
}
`

应该像这样使用相应的 useQuery 钩子,并将 courseId 参数设置为 string 而不是 any 因为查询需要一个字符串

const AnalyticsStatistic = (courseId: string) => {
                                           //? FIX 
 const { loading, error, data } = useQuery(GET_ANALYTICS,{
  variables: {courseId},
})

如果您得到未使用的变量,则将其添加到 tsconfig.json

{
  "compilerOptions": {
    "noUnusedLocals": false,
    "noUnusedParameters": false
  }
}

【讨论】:

  • 还没有,我还为我的问题添加了屏幕截图,您可以检查一下吗?
  • 我已经更新了我的答案尝试在 tsconfig.json 中设置这些标志
  • 是否设置为假?如果为真,则将其更改为假
  • 我添加了,你能检查一下吗?
  • 上帝保佑你,伙计
猜你喜欢
  • 2022-12-22
  • 2018-01-07
  • 2019-05-04
  • 2018-10-07
  • 2020-02-17
  • 2021-08-29
  • 2020-08-06
  • 2020-01-08
  • 1970-01-01
相关资源
最近更新 更多