【问题标题】:React Native setState not working when I loop through an array当我遍历数组时,React Native setState 不起作用
【发布时间】:2020-08-02 08:55:26
【问题描述】:

我有一个存储帖子的所有 uuid 的状态。我正在从 firebase 检索 useEffect() 中帖子的 uuid,并遍历 uuid 数组并检索用户发布的所有帖子,但帖子状态返回一个空数组。

useEffect(() => {
  getData();
}, []);

const getData = () => {
  setPosts([]);
  setPostuuids([]);

  firebase
    .firestore()
    .collection("users")
    .doc(uid)
    .get()
    .then((doc) => {
      setPostuuids(doc.data().posts);
    });

postuuids.filter((postuuid) => {
  firebase
    .firestore()
    .collection("posts")
    .doc(postuuid)
    .get()
    .then((doc) => {
      const image = doc.data().image;
      const text = doc.data().text;
      const userid = doc.data().uid;
      const timestamp = doc.data().timestamp;
      const username = doc.data().username;
      const uuid = doc.data().uuid;
      const name = doc.data().name;
      const avatar = doc.data().avatar;

      setPosts((prevPosts) => [
      ...prevPosts,
      {
        image: image,
        timestamp: timestamp,
        text: text,
        name: name,
        userid: userid,
        uuid: uuid,
        username: username,
        avatar: avatar,
       },
      ]);
    });
  });
};

【问题讨论】:

  • 我没有深入研究您的代码,但考虑到 setState(也带有钩子)是异步的。
  • 试试这个:jsfiddle.net/y1uLpq5d 有用吗?
  • 我其实是在使用功能组件和钩子

标签: reactjs firebase react-native google-cloud-firestore setstate


【解决方案1】:

您的 postuuids.filter 在请求完成之前运行,因此 postuuids 为空。 您应该为 postuuids.map() 使用另一个 useEffect():

useEffect(() =>{

postuuids.map((postuuid) => {
  firebase
    .firestore()
    .collection("posts")
    .doc(postuuid)
    .get()
    .then((doc) => {
      const image = doc.data().image;
      const text = doc.data().text;
      const userid = doc.data().uid;
      const timestamp = doc.data().timestamp;
      const username = doc.data().username;
      const uuid = doc.data().uuid;
      const name = doc.data().name;
      const avatar = doc.data().avatar;

      setPosts((prevPosts) => [
      ...prevPosts,
      {
        image: image,
        timestamp: timestamp,
        text: text,
        name: name,
        userid: userid,
        uuid: uuid,
        username: username,
        avatar: avatar,
       },
      ]);
    });
  });
};

},[postuuids])

【讨论】:

    【解决方案2】:

    使用 ma​​p 方法而不是 filter 来循环列表。

    最好的问候!

    【讨论】:

    • 我用 map 尝试了同样的事情,结果是一样的。
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2019-02-18
    • 2020-09-15
    相关资源
    最近更新 更多