You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API返回值传入useState作为React Rating组件的初始值

问题核心原因

  • 你的movieData是数组类型,直接通过movieData.vote_average读取属性会返回undefined,自然无法给Rating组件赋默认值。
  • 你定义的ratingValue是全局公共状态,所有渲染出来的电影卡片会共用这一个评分值,修改任意一个卡片的评分,所有卡片的评分都会同步变更,不符合业务需求。

适配多电影独立评分的修改方案

如果需要同时渲染多个电影,且每个电影的评分独立修改,按如下代码调整即可:

const Produts = () =>{
  const classes = useStyles();
  // 初始化数据时给每个电影加独立的自定义评分字段,默认值用接口返回的vote_average
  const [movieData, setMovieData] = useState([
    {
        "adult": false,
        "backdrop_path": "/7RyHsO4yDXtBv1zUU3mTpHeQ0d5.jpg",
        "genre_ids": [12,878,28],
        "id": 299534,
        "original_language": "en",
        "original_title": "Avengers: Endgame",
        "overview": "After the devastating events of Avengers: Infinity War, the universe is in ruins due to the efforts of the Mad Titan, Thanos. With the help of remaining allies, the Avengers must assemble once more in order to undo Thanos' actions and restore order to the universe once and for all, no matter what consequences may be in store.",
        "popularity": 326.894,
        "poster_path": "/or06FN3Dka5tukK1e9sl16pB3iy.jpg",
        "release_date": "2019-04-24",
        "title": "Avengers: Endgame",
        "video": false,
        "vote_average": 8.3,
        "vote_count": 18957,
        // 新增自定义评分字段,默认值取接口返回的评分
        customRating: 8.3
    },
    // 其他电影数据同理补充customRating字段即可
  ]);

  // 抽离评分更新方法,根据电影ID修改对应项的评分
  const handleRatingChange = (movieId, newRating) => {
    setMovieData(prev => prev.map(movie => {
      if (movie.id === movieId) {
        return {...movie, customRating: newRating}
      }
      return movie
    }))
  }

  return (
    <> 
      <div className={classes.main}> 
        {movieData.map((movie) =>{
          return(
            <Card className={classes.cardMain} key={movie.id}>
              <CardActionArea>
                <CardMedia className = {classes.cardImage}>
                  <img style = {{width: '100%', height: '100%', objectFit: 'cover'}} 
                    src ={`https://image.tmdb.org/t/p/original${movie.poster_path}`} 
                    alt = "movie poster"/>
                </CardMedia>
                <CardContent className = {classes.cardContent}>
                  <Typography>  {movie.original_title} </Typography>
                  <Typography 
                    className = {classes.typography1} 
                    variant="body2" 
                    component = "p"
                  > {movie.release_date} 
                  </Typography>
                  <Rating 
                    className = {classes.typography2} 
                    name = {`ratings-${movie.id}`}
                    // 取当前电影的独立评分
                    value = {movie.customRating}
                    // 传入当前电影ID更新对应评分
                    onChange = {(event, newRating) => handleRatingChange(movie.id, newRating)}
                  />  
                </CardContent>
              </CardActionArea>
              <CardActions >
                <Button className = {classes.cardButton} >Watch</Button>
                <Button className = {classes.cardButton}>Like</Button>
                <Button className = {classes.cardButton}>Rent</Button>
              </CardActions>
            </Card>
          );
        })}
      </div>
    </>
  )
};
export default Produts;

如果你后续是从接口拉取movieData数据,拉取成功后遍历给每一项加customRating: item.vote_average再存入state即可,逻辑和上面一致。


单条电影场景的简化方案

如果你只需要渲染单条电影数据,直接把movieData的初始值从数组改成单个对象即可:

// 初始值直接存单个电影对象,不需要包数组
const [movieData, setMovieData] = useState({
  "adult": false,
  "backdrop_path": "/7RyHsO4yDXtBv1zUU3mTpHeQ0d5.jpg",
  // 其他字段省略
  "vote_average": 8.3,
})
// 直接用接口返回的评分作为初始值即可
const [ratingValue, setRatingValue] = useState(movieData.vote_average)

内容的提问来源于stack exchange,提问作者Tapesh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:15:05