【问题标题】:Apollo reactive variable are not working when imported into another file! Why?导入另一个文件时,Apollo 反应变量不起作用!为什么?
【发布时间】:2020-12-31 21:51:55
【问题描述】:

src/another_folder/reactiveVarInitializationFile.js 从“@apollo/client”导入 {makeVar}

export const selectStore = makeVar('')

//我的组件

import {Select,Spin} from "antd"
import {selectStore} from "../../reactives/selectStore.RV"
import {useQuery} from "@apollo/client"
import FETCH_STORES from "../../queries/getStoresSelectSoreDPD"
export default function(){
    const {data}= useQuery(FETCH_STORES)
    const store = selectStore()
    const onChange=(val)=>{
        console.log(val)
        selectStore(val)
    }
    console.log(store)
    return(
    <>
        {!data?(<Spin/>):(
            <Select
                style={{width:"200px"}}
                placeholder="Select store" 
                onChange={onChange}>
                {data.currentUser.outlets.map(el=><Select.Option key={el.id} value={el.id}>{el.name} 
               </Select.Option>)}        
            </Select>
            
        )}
        <p>{store}</p>
    </>
    )
}

问题是当我将 selectStore 导入组件时,我无法通过 selectStore() 获取其值或通过执行 selectStore("new value") 修改 var

谁能帮帮我?

【问题讨论】:

    标签: reactjs apollo react-apollo apollo-client apollo-server


    【解决方案1】:

    此答案已过时,因为 useReactiveVar 已启动

    如果您想要重新渲染,则需要在查询中使用反应性变量。这是关于它的官方文档:

    顾名思义,反应式变量可以触发应用程序中的反应式变化。每当您修改反应性变量的值时,依赖于该变量的查询会刷新,并且您的应用程序的 UI 会相应更新。

    因此您需要为 selectStore 字段编写读取策略。然后像这样在查询中使用这个字段:

     const { data } = useQuery(gql`
       query GetSelectStore {
        selectStore @client
      }
     `);
    

    【讨论】:

    • 我不明白downvote :D 在 useReactiveVar 钩子介绍之前;这是使用响应式变量并对其更改做出反应的唯一方法。
    【解决方案2】:

    如果直接使用 reactiveVar,它不会在值更改时更新,它只会在初始渲染时更新。

    但是,如果您希望它在值更改时更新并触发重新渲染,则需要使用 useReactiveVar 挂钩:https://www.apollographql.com/docs/react/local-state/reactive-variables/

    所以,是这样的:

    const store = useReactiveVar(selectStore);
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2017-10-12
      • 2023-01-30
      • 2020-02-09
      • 2021-08-22
      • 1970-01-01
      • 2013-06-19
      相关资源
      最近更新 更多