首页 > 解决方案 > 导入另一个文件时,Apollo 反应变量不起作用!为什么?

问题描述

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

导出 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

谁能帮帮我?

标签: reactjsapolloreact-apolloapollo-clientapollo-server

解决方案


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

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

所以,像这样:

const store = useReactiveVar(selectStore);

推荐阅读