导入另一个文件时,Apollo反应变量不起作用!为什么?

问题描述

src / another_folder / reactiveVarInitializationFile.js 从“ @ apollo /客户端”导入{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

有人可以帮我吗?

解决方法

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

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

所以,像这样:

select_features(...)
,

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

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

因此,您需要为selecStore字段编写一个读取策略。然后在查询中使用此字段,如下所示:

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