[英]React firebase get data from .on('value')
我在反应中从 firebase 获取数据,但我无法传递该数据,因为变量是在内部定义的。 以下是我想要做的。
function getCommentNums(item){
const formRef = database.ref(
`/comments/${form_id}/${instanceId}/${item.id}`
);
console.log('formref = ', formRef)
formRef.on('value', async(snap)=>{
const commentsArr = (await snap.val()) ?? [];
console.log('commentArr=', commentsArr.length)
setCommentLen(commentsArr.length)
})
return someNum
}
然后在主返回语句中 getcommentnums 在手风琴内被调用
{questions.map((item, index) => (
<Accordion
key={index}
id={
"question-" +
(noOfQuestionsPerPage * (page - 1) + 1 + index)
}
question={item}
questionNo={noOfQuestionsPerPage * (page - 1) + 1 + index}
//match vs item.id
commentNums = {getCommentNums(item)}
onBlur={handleClickSave}
onClickComments={onClickComments}
onChangeAnswer={onChangeAnswer}
answers={answers}
onClickLastValue={onClickLastValue}
disabled={form.is_submitted}
/>
))}
我正在尝试将 someNum 设置为commentsArr.length
,它应该是一些 integer。 这个 function 将在某些子组件中调用以显示 commentNums 的值。 多个子组件将在一个页面上,每个子组件都将在 fn 上方调用以获取相应的 commentNums。
我曾尝试使用 set state,但这只会导致无限循环。
有人可以告诉我如何向前发送commentArr.length
值吗?
当您调用setCommentLen(commentsArr.length)
来更新commentLen
state 变量时,您的渲染代码仍会尝试渲染getCommentNums
的返回值,这将不起作用。
实现这一点的正确方法是:
修改你的加载器 function 以不再返回任何值,只更新 state。
function loadCommentCount(item){ const formRef = database.ref(`/comments/${form_id}/${instanceId}/${item.id}`); formRef.on('value', async(snap)=>{ const commentsArr = (await snap.val())?? []; setCommentLen(commentsArr.length) }) }
在渲染代码之外调用这个加载器 function,例如在创建组件时,通常在useState
处理程序中。
useState(() => { questions.map((item, index) => ( loadCommentCount(item); }) }, [questions])
然后渲染来自 state 的值。
commentNums = {commentCount}
另见:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.