Reactjs循环遍历数组和切换

时间:2017-08-30 16:00:42

标签: json reactjs

我有一个reactjs组件,我试图用循环和切换来渲染数据。

我尝试了一张地图,然后是一张forEach - 但它声称它不是一个功能。

json看起来像这样。

// JSON

"contents": {
          "0": ["emotional distress", "behavioural difficulties", "hyperactivity and concentration difficulties", "difficulties in getting along with other young people"],
          "5": ["kind and helpful behaviour"]
        }

//组件

var YourCurrentStanding = React.createClass({

    alertLevel: function (key) {
      switch (key) {
        case '0': return "very high";
        case '1': return "high";
        case '5': return "very low";
        default: return "xy";
      } 
    },

    render: function () {
        console.log('this.props.data.contents', this.props.data.contents)
        return (
            <div>
                {
                  this.props.data.contents.forEach(function(j) {
                    return <p key={j}>Score for x,y and z {this.alertLevel(j)}</p>
                  })
                }
            </div>
        );
    }
});

-----------应该读起来像

"<p>Score for emotional distress, behavioural difficulties, hyperactivity and concentration difficulties very high and difficulties in getting along with other young people very high</p>

<p>Score for kind and helpful behaviour very low</p>"

附近添加了语法检查的工作代码

var YourCurrentStanding = React.createClass({

    grammarCheck : function(vals) {
      //x,y,z and d
      //z

      return vals.join(', ')
    },


    alertLevel: function(key) {
      switch (key) {
        case "0":
          return "very high";
        case "1":
          return "high";
        case "5":
          return "very low";
        default:
          return "xy";
      }
    },

    render: function() {
      return (
      <div>
        {Object.keys(this.props.data.contents).map((key, index) => {      
            return <p key={index}>Score for {this.grammarCheck(this.props.data.contents[key])} is <b>{this.alertLevel(key)}</b></p>
        })}
      </div>
      );
    }
});

3 个答案:

答案 0 :(得分:1)

这是:(为演示取样数据对象)

var data = {
  contents: {
    "0": [
      "emotional distress",
      "behavioural difficulties",
      "hyperactivity and concentration difficulties",
      "difficulties in getting along with other young people"
    ],
    "5": ["kind and helpful behaviour"]
  }
};

var YourCurrentStanding = React.createClass({
  alertLevel: function(key) {
    switch (key) {
      case "0":
        return "very high";
      case "1":
        return "high";
      case "5":
        return "very low";
      default:
        return "xy";
    }
  },
  
  joinContents: function(data, key) {
    return [ data[key].slice(0, -1).join(", "), data[key].slice(-1)[0]         
           ].join(data[key].length < 2 ? "" : " and ");
     
    /*
     data[key].slice(0, -1).join(", "): takes all keys except last and joins them together with a comma.
     data[key].slice(-1)[0]: Last key
    */
  },

  render: function() {
    return (
      <div>
        {Object.keys(data.contents).map((key, index) => {
          return (
            <p key={index}>
              Score for {this.joinContents(data.contents, key)} is {" "}
              <b>{this.alertLevel(key)}</b>
            </p>
          );
        })}
      </div>
    );
  }
});

ReactDOM.render(<YourCurrentStanding />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>

答案 1 :(得分:0)

只需使用箭头功能。正如@cesar威廉所说,照顾对象属性。

render: function () {
    console.log('this.props.data.contents', this.props.data.contents)
    return (
        <div>
            {
              Object.keys(this.props.data.contents).map((key, index) => 
              {
                return <p key={index}>Score for xx {this.alertLevel(this.props.data.contents[j])}</p>
              })
            }
        </div>
    );
}

我并没有真正看到你的jsx段落,但这是一个好的开始。

编辑:你永远不应该使用索引作为键,找到更适合的东西,它只是用于示例

答案 2 :(得分:0)

您无法通过forEach或map方法迭代对象。

const contentKeys = Object.keys(this.props.data.contents);
contentKeys.map(function(key, index) {
    const item = this.props.data.contents[index];
    return <p key={index}>Score for xx {this.alertLevel(item)}{index !== contentKeys.length-1 ? ', ' : null}</p>
});

使用索引或项目调用alertLevel方法 - 它取决于您。

相关问题