javascript - 更改后的反应状态未呈现
问题描述
我在这个组件中使用 Firebase 来检索一些基本用户详细信息的数组。此查询的数组大小始终为 3。执行此操作的函数是 whoToFollow(),当收到结果时,该函数更新状态变量“谁”这里没有发生数组突变。我只是将状态重置为返回值。不幸的是,尽管确认状态确实已更新,但组件并没有重新渲染以显示它。为了简化代码,我只使用了数组的长度作为要显示的值。
在代码下方,我包含了控制台日志的屏幕截图,其中显示了代码执行步骤并显示了对正在更改的状态值的确认。(返回数据由测试数据组成)
const storage = getStorage(firebaseApp);
const db = getFirestore();
function Aside() {
const [who, setWho] = useState([])
const whoToFollow = async () => {
const usersRef = collection(db, "users");
const q = query(usersRef, limit(3));
const querySnapshot = await getDocs(q);
const results = await querySnapshot.docs.map(doc => doc.data());
let filteredArray = []
results.forEach(async (user) => {
let imgPath = await getDownloadURL(ref(storage, user.profilePicture));
let tmpObj = {
uid: user.UID,
displayName: user.displayName,
userName: user.userName,
profilePicture: imgPath
};
filteredArray.push(tmpObj);
});
console.log('Users recieved and updating who state')
setWho(filteredArray)
}
useEffect(() => {
console.log('component did mount, calling "WhoToFollow()" function')
whoToFollow()
}, []);
useEffect(() => {
console.log('who state has been updated but nothing is being rendered?')
console.log(who)
}, [who]);
return (
<aside>
<div className='aside-head'>Search</div>
<div className='aside-cont'>
<div className='who-to-follow'>
<div className='wtf-head'>
New users to follow
</div>
<div className='wtf-list'>
{who.length}
</div>
</div>
</div>
</aside>
);
}
export default Aside;
解决方案
推荐阅读
- git - 这两个更新最新子模块的 git 命令有什么区别?
- fluentd - 如何在fluentd中制作嵌套3级?
- autodesk-forge - rvt 文件的 Autodesk-forge 翻译失败
- python - 停止执行代码,直到通过 webhook 提供结果
- matlab - 在MATLAB潮流计算中,矩阵为奇异值
- mobile - 生物识别移动登录的流程是什么?服务器端需要改变吗?
- javascript - Javascript对数组中的数组进行计数
- angular - 调用observer.complete()时如何返回值
- cadence-workflow - 如何按节奏动态创建工作流
- html - 试图从 Apache Web 服务器中的 USB 获取文件