Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - Go over an object, and return a component to each attribute in the object

Hi everyone I'm new to react, I built component - I have a state of user preferences - and I do go over all preferences, and return the rating he gave to each preference - with the help of mui - I have been trying for several hours to do this, I can not.

This is the code I wrote, it runs but I do not get the component back, I do not understand why.

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;

I think the problem is very small, but I can not find it, I just want to go over my object and for each feature, return a "rating" component of "materialUi".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first problem of your code was that you didn't use this.state.preferences. The second problem was you are confused about the usage of {} and () parentheses in JS. The third point - Do not forget to print key when you output a list of elements.

I have edited your code. Here is a working example on codepen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...