reactjs - 导入另一个文件时,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
谁能帮帮我?
解决方案
如果直接使用 reactiveVar,它不会在值更改时更新,它只会在初始渲染时更新。
但是,如果您希望它在值更改时更新并触发重新渲染,则需要使用useReactiveVar
钩子:https ://www.apollographql.com/docs/react/local-state/reactive-variables/
所以,像这样:
const store = useReactiveVar(selectStore);
推荐阅读
- java - Spring Boot WS SOAP 端点是否能够以反应方式工作?
- python - 使用 numpy 数组/列表作为字符串的索引
- php - OctoberCMS:附加关系时如何使用延迟绑定?
- ef-core-3.1 - EF Core 3.1 搜索过滤器
- vue.js - VueJs 导出表格数据
- firebase - 如何在具有多个路由的 SPA 中保存读取,这些路由不断获取相同的数据,而这些数据从那以后就没有改变?
- php - 使用图像文件链接显示随机横幅
- ssl - TLS 证书主题(CN、OU 和 O)
- typescript - Typescript类型/接口来描述接口方法
- java - JavaFX 在 UI 中的两个窗格之间切换