如何从组件道具传递 useQuery 变量?

How can I pass useQuery variable from component prop?

我有这个问题:

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' 已声明,但其值永远不会是 read.ts(6133) 重复标识符 'courseId'.ts(2300)

对于内部变量:{courseId} 正在获取这些 errors:Duplicate 标识符 'courseId'.ts(2300) 绑定元素 'courseId' 隐式具有 'any' type.ts(7031)

for inside courseId

for outside courseId

problems in console

您的 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
  }
}