[英]How to get value of useState variable in function that passed to another component
The best way to describe question is my code:描述问题的最佳方式是我的代码:
function EstateParamsList({ estateType, category }) {
const [isLoading, setIsLoading] = useState(true)
const [params, setParams] = useState({})
const [showPopUp, setShowPopUp] = useState(false)
useEffect(() => {
if (category && typeof category.id !== undefined) {
return db.collection(`dictionaries/ESTATE_PARAMS/${estateType}/${category.id}/params`).onSnapshot(response => {
const paramsObject = {}
response.forEach(param => {
paramsObject[param.id] = {
...convertParamObjetcToFieldsConfig(param.data()),
change: fieldChangedHandler
}
})
setParams(paramsObject)
setIsLoading(false)
})
} else {
setIsLoading(false)
}
}, [category])
console.log(params)
const fieldChangedHandler = (event, fieldIdentifier) => {
if(params)
console.log(params)
}
So i have params variable, that im init with object, that i'm getting async from firebase.所以我有参数变量,我用 object 初始化,我从 firebase 获得异步。 Implementation of initializing you can see in useEffect method .
您可以在useEffect 方法中看到初始化的实现。 For every object i want to pass ref for the function "fieldChangedHandler", for managing value of inputs.
对于每个 object,我想传递 function“fieldChangedHandler”的 ref,用于管理输入值。
fieldChangedHandler is a method of my EstateParamsList . fieldChangedHandler是我的EstateParamsList的一种方法。 But there i cant get value of params!
但是我无法获得参数的价值!
Question is WHY?问题是为什么? I'm calling fieldChangedHandler only after everything was rendered, and async request was done.
只有在所有内容都渲染完毕并且异步请求完成后,我才调用 fieldChangedHandler。
Below is console log of params.下面是参数的控制台日志。 Why in func is empty params ?
为什么 func 中的参数是空的?
Calling:来电:
const renderParamsAsFields = params => {
const fields = []
for (const key in params) {
fields.push(<Field {...params[key]} changed={event => params[key].change(event, key)} />)
}
return fields.length ? fields : <div className='EstateParamsManager-EmptyValues'>Нет параметров</div>
}
Why not use curried function?为什么不使用咖喱 function?
const createFieldChangedHandler = (
params,
fieldIdentifier
) => event => {
if (params) console.log(params);
};
function EstateParamsList({ estateType, category }) {
//... other code
useEffect(() => {
//...other code
change: createFieldChangedHandler(
paramsObject,
param.id
),
//...other code
}, [category, estateType]);//fixed missing dependency
When you call the change function you should already have the right values in scope:当您调用更改 function 时,您应该已经在 scope 中拥有正确的值:
<Field {...params[key]} changed={params[key].change} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.