简体   繁体   English

useEffect hook 未正确设置 state object

[英]useEffect hook not setting state object properly

Ok I literally cannot figure out why this is happening.好的,我真的无法弄清楚为什么会这样。 I am doing this same thing on different components and sometimes it works and sometimes it doesn't.我在不同的组件上做同样的事情,有时它有效,有时它不。 I use the useEffect hook to get an object from my firebase storage.我使用 useEffect 挂钩从我的 firebase 存储中获取 object。 I get the object properly as shown in my console but I literally cannot access any nested values.我得到了正确的 object,如我的控制台所示,但实际上我无法访问任何嵌套值。

Code:代码:

const ReviewComponent = (props) => {
  const [open, setOpen] = useState(false)
  const [campaigns, setCampaigns] = useState([])
  const [currentCampaign, setCurrentCampaign] = useState([])

//First useEffect hook used for something else in the code
  const tempDoc = []
      useEffect(() => {
        var docRef = db.collection("campaigns");
        docRef.get().then(function(querySnapshot) {
          querySnapshot.forEach(function(doc) {
            tempDoc.push({ id: doc.id, ...doc.data() })
              // doc.data() is never undefined for query doc snapshots
              setCampaigns(tempDoc)
          });
      })
      .catch(function(error) {
          console.log("Error getting documents: ", error);
      });
      },[]);


//Second use effect hook (THIS IS THE ONE CAUSING ISSUES)
      useEffect(() => {
        const docRef = db.collection("campaigns").doc(slug);
    
        docRef.get().then(function(doc) {
            if (doc.exists) {
                console.log("Document data:", doc.data());
                setCurrentCampaign(doc.data()) 
            } else {
                // doc.data() will be undefined in this case
                console.log("No such document!");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
      });
    },[]);


  const handleOpen = () => {
    setOpen(true)
  };

  const handleClose = () => {
    setOpen(false);
  };

  if(currentCampaign[0]) { // Or if(campaign[0])

    console.log(currentCampaign) //this never gets logged 
  }

  return(
    <Typography>
    {currentCampaign.reviews[0].text} // TypeError: Cannot read property 'text' of undefined, if I do currentCampaign.reviews -> TypeError: Cannot read property 'reviews' of undefined
   </Typography>
)

文本

As you can the above picture shows the object logged from within the useEffect hook.如您所见,上图显示了从 useEffect 挂钩中记录的 object。 I try logging it by checking is currentCampaign[0] exists.我尝试通过检查 currentCampaign[0] 是否存在来记录它。 It never exists.它永远不存在。 If I do currentCampaign.body or any other top level elements, it works fine in my return statement.如果我执行 currentCampaign.body 或任何其他顶级元素,它在我的 return 语句中工作正常。 If I do anything nested such as currentCampaign.images[0].url -> ERROR:如果我做任何嵌套的事情,例如 currentCampaign.images[0].url -> 错误:

I can get access to all the top level properties such as body, campaignPolicy etc. but if I do我可以访问所有顶级属性,例如 body、campaignPolicy 等,但如果我这样做了

TypeError: Cannot read property 'seconds' of undefined TypeError:无法读取未定义的属性“秒”

If I do campaign.startDate.seconds i get same error:如果我做campaign.startDate.seconds 我得到同样的错误:

TypeError: Cannot read property 'seconds' of undefined TypeError:无法读取未定义的属性“秒”

if(currentCampaign[0]) { // Or if(campaign[0])
    console.log(currentCampaign) //this never gets logged 
}

You can't request the state value at the root level of ReviewComponent component, which means the same level of the state definition.您不能在ReviewComponent组件的根级别请求 state 值,这意味着与 state 定义相同的级别。 This is called once initially when the component is rendered, so currentCampaign is always empty.这在组件渲染时最初调用一次,因此 currentCampaign 始终为空。

You should use this inside the useEffect with adding a state dependency.您应该在useEffect中使用它并添加 state 依赖项。

useEffect(() => {
  if(currentCampaign[0]) {
    console.log(currentCampaign)
  }
}, [currentCampaign]);

return(
    <Typography>
       {currentCampaign.reviews[0].text}
   </Typography>

Regarding this error, currentCampaign is initially empty array, so at the first time of this component rendering, currentCampaign.reviews will be undefined.关于这个错误,currentCampaign 最初是空数组,所以在这个组件第一次渲染时,currentCampaign.reviews 将是未定义的。 Thus currentCampaign.reviews[0].text will be the error.因此currentCampaign.reviews[0].text将是错误。

You should always check currentCampaign if it is undefined or not.您应该始终检查currentCampaign是否未定义。

FYI, currentCampaign is array in your state definition, so try to correct the syntax to request currentCampaign variable.仅供参考, currentCampaign是您的 state 定义中的数组,因此请尝试更正语法以请求currentCampaign变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM