首页 > 解决方案 > 更改后的反应状态未呈现

问题描述

我在这个组件中使用 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;

在此处输入图像描述

标签: javascriptreactjsfirebase

解决方案


推荐阅读