简体   繁体   English

React 状态 (useState) 不会随获取的数据更新

[英]React state (useState) doesn't update with fetched data

Background背景
I have a star rating system.我有一个星级评分系统。 When a user has already rated the content, I want them to be able to see their previous rating when the page loads.当用户已经对内容进行了评分时,我希望他们能够在页面加载时看到他们之前的评分。

I am able to fetch the rating data for the user and I have a set initial state for the star rating, just in case there isn't any rating yet.我能够为用户获取评级数据,并且我为星级评级设置了初始状态,以防万一还没有任何评级。

The Goal目标
The goal is to set the initial state for the star rating with a value of 0 .目标是将星级的初始状态设置为0值。 When the previously-stored rating value is fetched, I want the initial state value to update to the fetched rating value.当获取先前存储的评级值时,我希望初始状态值更新为获取的评级值。

The Problem问题
Currently, when the page loads, the star rating value says it's undefined , even though the stored rating value is fetched and appears in my console.目前,当页面加载时,星级值表示它是undefined ,即使存储的评级值被提取并出现在我的控制台中。 I'm pretty sure this is happening because the variable is being called before the data query has finished.我很确定这是因为在数据查询完成之前调用了变量。 Unfortunately, it doesn't update when it does finish.不幸的是,它在完成时不会更新。

Code代码

In the code below, articleRating is the fetched rating value在下面的代码中, articleRating是获取的评分值

// data query
const {
    data: { feedback, id: feedbackId, rating: articleRating },
    status: feedbackStatus,
  } = useGetFeedback(slug as string, "lesson")

// setting initial state for star rating
const [starsSelected, selectStar] = useState(0)

// Updating the rating value to show previously stored rating
useEffect(() => {
    if (articleRating !== null || articleRating !== "undefined") {
      console.log("rating value: ", articleRating)
      selectStar(articleRating)
    }
 }, [])

In the code above, I'm using the useEffect hook because I get an error message saying there are infinite renders without it and the page breaks.在上面的代码中,我使用了useEffect钩子,因为我收到一条错误消息,说没有它可以无限渲染并且分页符。

Thanks in advance for any advice!提前感谢您的任何建议! ✌️ ✌️

您的useEffect仅在第一次渲染时运行,您应该将articleRating添加到第二个参数中的依赖项数组,然后它只会在该变量更新时运行。

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

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