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

React Axios提交星级评分到MongoDB无法更新问题解决

问题修复方案

你的代码存在多处核心逻辑错误,逐一修复即可实现按collegeId更新、展示对应院校评分:

核心错误点

  • StarRating组件未正确绑定选中值、事件回调,星星颜色写死为前三颗常亮,不跟随选中状态变化
  • 组件state/setter命名混乱,传参时调用了不存在的函数
  • 评分查询、提交请求未携带collegeId参数,无法匹配Mongo中对应院校的评分数据
  • 接口拉取到的已有评分未同步到本地state,导致初始评分无法显示
  • 院校数据拉取的useEffect缺失依赖数组,会触发组件无限重渲染
  • Axios请求地址未加字符串引号,存在基础语法错误
  • 评分提交时未获取当前选中的星值,变量名冲突导致传参错误

修复后代码

1. 修复StarRating星级组件

const StarRating = (props) => {
  const { ratingValue, onRateChange } = props;
  return (
    <div>
      {Array(5)
        .fill(0)
        .map((_, idx) => {
          // 星级按1-5分计数,匹配索引+1
          const currentScore = idx + 1;
          return (
            <label key={idx} style={{cursor: 'pointer'}}>
              <input
                type="radio"
                name="rating"
                value={currentScore}
                checked={currentScore === ratingValue}
                // 选中时把当前分值传给父组件回调
                onChange={() => onRateChange(currentScore)}
                style={{display: 'none'}} // 隐藏原生单选框
              />
              {/* 星星颜色动态跟随选中值变化 */}
              <FaStar color={currentScore <= ratingValue ? "#01af93" : "#bbb"} size={20}/>
            </label>
          )
        })}
    </div>
  );
};

2. 修复Report页面组件

const Report = (props) => {
  const { advices } = useSelector((state) => state.advice);
  // 统一state命名:rate存当前评分,setRate为修改方法
  const [rate, setRate] = useState(0);
  // 从当前院校数据取collegeId,字段名按你实际的Mongo存储结构调整
  const currentCollege = advices?.[0] || {};
  const collegeId = currentCollege._id;

  // 补全依赖数组,避免无限重渲染
  useEffect(() => {
    if (!advices) {
      dispatch(fetchAdvices(history));
    }  
  }, [advices]); 

  // 按collegeId拉取对应院校的已有评分,切换院校时自动重新拉取
  useEffect(() => {
    if (!collegeId) return;
    async function fetchRate() {
      try {
        // get请求携带collegeId参数,地址补全引号
        const { data } = await axios.get(`http://localhost:8080/rating?collegeId=${collegeId}`);
        // 拉取到评分后同步到本地state
        setRate(data.rating || 0);
      } catch(error) {
          console.log(error);
      }
    };
    fetchRate();
  }, [collegeId]);

  // 选星时触发,接收当前选中的分值
  const handleRate = async(selectedScore) => {
    try {
      // 先更新本地state,实现选中效果即时反馈
      setRate(selectedScore);
      // 提交评分到后端,携带分值和对应院校id
      await axios.post("http://localhost:8080/rating", {
        rating: selectedScore,
        collegeId: collegeId
      });
    } catch(error) {
      console.log("评分提交失败", error);
    }
  }
   
  return (
    <>
      <Container> 
        <Grid>
          <Fragment>
            <Grid>
              <Card>
                <CardContent>
                  <div>
                    {currentCollege.college_name}
                    <StarRating 
                      ratingValue={rate} 
                      onRateChange={handleRate} 
                    />
                  </div>
                </CardContent>
              </Card>
            </Grid>
          </Fragment>
        </Grid>
      </Container>
    </>
  )};

后端接口配套逻辑

  • GET /rating接口需要从请求参数中读取collegeId,查询Mongo中对应院校的评分记录返回
  • POST /rating接口从请求体读取rating和collegeId,做upsert操作:该院校已有评分则更新分值,无记录则新建评分条目
  • 如果需要区分不同用户的评分,请求中额外携带当前登录用户的userId即可,避免不同用户评分互相覆盖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:57:28