在地图循环中计算jsx

时间:2017-03-02 09:26:52

标签: javascript reactjs jsx

{items.filter(item => item.status === 'active').map(item =>
    let total_male = item.length + 1;
    <p>Male ({total_male})</p>
    {this.renderData(item)}
    </div>
)}

以上jsx有效吗?这对我来说很有意义,但它有错误。我有一个像这样的json

[{"name":"james","satus":"active"},{"name":"alice","satus":"deactived"}]

我想计算状态有效的obj长度。

3 个答案:

答案 0 :(得分:1)

像这样写:

&#13;
&#13;
var a = [
           {"name":"james","status":"active"},
           {"name":"alice","status":"deactived"}
];

class App extends React.Component { 

    _createList() {
       let count=0, active;
       active = a.filter(item => item.status === 'active');
       count = active.length;
       return active.map(item => <div>
              <p>Male Count: {count}</p>
              {this.renderData(item)}
            </div>
        )
       }
       
       renderData(item){
          return <div>{item.name}</div>
       }

    render() {
        return (
            <div>
               {this._createList()}
            </div>
        )
    }
}


ReactDOM.render(<App />, document.getElementById('container'));
&#13;
<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='container'/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您提供的jsx无效,因为:

  • </div>但没有开始标记<div>
  • 箭头功能有语法错误
  • 箭头功能没有退货声明
  • item对象没有length属性(来自您提供的JSON数据)。也许您打算使用items.length代替?

修复它:

{items.filter(item => item.status === 'active').map(item => {
    let total_male = items.length + 1;
    return (
        <div>
            <p>Male ({total_male})</p>
            {this.renderData(item)}
        </div>
    );
})}

答案 2 :(得分:0)

尝试

{items.filter(item => item.status === 'active').map(item =>{
    let total_male = item.length + 1;
    return (
        <div>
            <p>Male ({total_male})</p>
            {this.renderData(item)}
        </div>
        )}
)}

你忘记了回归并关闭了div。