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

React遍历偏好对象渲染Material UI Rating组件失败求助

解决你的Profile组件Rating渲染问题

嘿,我看到你卡在这个小问题上啦,其实就是几个容易忽略的细节,咱们来一一修正:

问题点梳理

  • 未正确访问state中的preferences:类组件里的state属性必须通过this.state来访问,你直接写preferences会导致变量未定义。
  • map函数缺少返回值:你的箭头函数用了大括号{}但没有显式return组件,这样遍历后不会生成任何DOM元素。
  • parseInt的基数参数未定义:base是未声明的变量,应该传入10表示十进制解析。
  • 错误地将JSX包裹在对象中:profilePreferences被赋值为一个对象,但render需要返回JSX元素,要去掉外层的{}。

修正后的完整代码

import React, { Component, Fragment } from 'react'; 
// MUI stuff 
import Rating from '@material-ui/lab/Rating'; 
// Icons 
import ListIcon from '@material-ui/icons/List'; 

class Profile extends Component { 
  constructor(props) { 
    super(props); 
    this.state = {
      preferences: { 
        html: "5", 
        react: "4", 
        css: "4", 
        angular: "3" 
      }
    }; 
  } 
  render() { 
    const { preferences } = this.state; // 解构state里的preferences,方便后续使用
    let profilePreferences = preferences && ( 
      <Fragment> 
        <ListIcon color="primary" /> 
        <hr /> 
        { Object.keys(preferences).map(prefer => (
          // 用小括号让箭头函数自动返回组件,也可以写成{ return <Rating ... /> }
          <Rating 
            key={prefer} // 遍历列表要加唯一key,避免React警告
            name={prefer} 
            defaultValue={parseInt(preferences[prefer], 10)} 
            precision={1} 
            readOnly
          />
        )) } 
        <hr /> 
      </Fragment> 
    ); 
    return profilePreferences ; 
  } 
} 
export default Profile;

额外优化说明

我还加了key={prefer},这是React遍历列表时的要求,用来帮助React识别每个元素的唯一性,避免控制台出现警告。

这样修改后,你的Rating组件应该就能正常渲染啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:14:40