我正在react中从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
}
然后在主返回语句中,在手风琴内部调用getcommentnum
{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
,它应该是某个整数。这个函数将在一些子组件中被调用,以显示commentNums的值。多个子组件将出现在一个页面上,每个子组件都会调用上面的fn来获得相应的评论。
我尝试过使用set state,但这只会导致无限循环。
有人能告诉我如何转发commentArr.length
值吗?
当您调用setCommentLen(commentsArr.length)
来更新commentLen
状态变量时,您的渲染代码仍然试图渲染getCommentNums
的返回值,但这不会起作用。
实现这一点的正确方法是:
-
修改加载程序函数,使其不再返回任何值,并且仅更新状态。
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) }) }
-
在呈现代码之外调用此加载程序函数,例如在创建组件时,通常在
useState
处理程序中。useState(() => { questions.map((item, index) => ( loadCommentCount(item); }) }, [questions])
-
然后呈现状态中的值。
commentNums = {commentCount}
另请参阅:
- 设置状态后React未更新渲染
- 如何将值从Firebase返回到react组件
- Firebase响应太慢
- 我的firebase实时推送键在react native中保存到数组中时发生了更改
- React本机阻止函数异步执行