【问题标题】:Reactjs looping through array and switchReactjs循环遍历数组并切换
【发布时间】:2017-08-30 16:00:41
【问题描述】:

我有一个 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>
      );
    }
});

【问题讨论】:

  • 使用 () => {} 函数语法,因为您的“this”不是绑定到您的组件而是绑定到您的匿名函数。 (我说的是你的 this.alertLevel)
  • 我把那个放在哪里 -- 我倾向于使用 var that = this -- 然后调用 that.alertLevel(j)
  • Contents 不是数组而是对象。所以它没有 forEach 方法。您必须遍历对象键,然后遍历数组。
  • 用map方法?
  • -- 我可以改变数据结构 -- 只是我觉得 0 - 非常高, - 1,高 -- 在键中使用数字而不是单词 -- 将能够确保数据排序正确

标签: json reactjs


【解决方案1】:

这里是:(以示例 data 对象进行演示)

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"/>

【讨论】:

  • 这很接近——你如何用 xxx 替换值——“情绪困扰,行为困难”——就像连接值数组一样
  • 需要添加逗号 - 并删除尾随逗号
  • 这应该对你有帮助,现在你应该能够关联和修改东西了
  • 它并不完全正确——它会产生单独的句子——何时应该将它们分组......例如......“

    情绪困扰、行为困难、多动和注意力集中困难的得分非常高,并且与其他年轻人相处的困难非常高

    善良和乐于助人的行为得分非常低

    "
  • @TheOldCounty,哦,我没看清楚。更新了 sn-p。
【解决方案2】:

这样使用箭头函数即可。正如@cesar william 所说,注意对象属性的映射。

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 段落,但这是一个好的开始。

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

【讨论】:

  • -- 映射数据的更好方法是什么? -- 我用数字作为关键,以确保它首先按严重程度排序 -- 0 - 非常高 - 1 - 高,5 - 非常低
【解决方案3】:

您不能通过 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 方法 - 由您决定。

【讨论】:

  • --这会产生内容,但没有逗号分隔
  • 刚刚添加了一个语法检查功能——所以也许 if(vals.length > 1){ vals.join(", ") //把最后一个逗号替换成一个 and } else { vals.join( ",") }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 2021-04-26
  • 2014-06-04
  • 1970-01-01
相关资源
最近更新 更多