首页 > 解决方案 > 遍历一个对象,并为对象中的每个属性返回一个组件

问题描述

大家好,我是新手,我构建了组件-我有一个用户偏好状态-我确实检查了所有偏好,并在 mui 的帮助下返回了他对每个偏好的评分-我一直在尝试几个小时才能做到这一点,我做不到。

这是我编写的代码,它运行但我没有取回组件,我不明白为什么。

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() {
    let profilePreferences = {preferences && (
                <Fragment>
                  <ListIcon color="primary" />
                  <hr />
                  {
                    Object.keys(preferences).map(prefer => {<Rating name={prefer} defaultValue={parseInt(preferences[prefer], base)} precision={1} readOnly/>}) 
                  }
                  
                  <hr />
                </Fragment>
              )}
    return profilePreferences ;
  }
}

export default Profile;

我认为问题很小,但我找不到它,我只想检查我的对象并为每个功能返回“materialUi”的“评级”组件。

标签: javascriptreactjs

解决方案


目前,preferences未定义。你需要从this.state.

render() {
    const { preferences } = this.state; // <------ Add this line
    let profilePreferences = {preferences && (
                <Fragment>
                  <ListIcon color="primary" />
                  <hr />
                  {
                    Object.keys(preferences).map(prefer => (<Rating name={prefer} defaultValue={parseInt(preferences[prefer], base)} precision={1} readOnly/>)) 
                  }
                  
                  <hr />
                </Fragment>
              )}
    return profilePreferences ;
  }

推荐阅读