React - 如何从其他数组进程的结果显示数组长度

时间:2018-03-10 13:04:09

标签: arrays reactjs

我想从其他数组进程的结果中显示数组长度。 我有一个数组包含3个对象,并希望获得失败的结果属性长度。

代码:

import React, { Component } from 'react';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            arrays: []         
        };
    }

    componentDidMount () {
        this.getData();
    }

    getData = () => {
        const arrays = [
            {
                name: 'one',
                value: '1',
                result: 'failed'
            },
            {
                name: 'two',
                value: '2',
                result: 'success'
            },
            {
                name: 'three',
                value: '3',
                result: 'failed'
            }
        ];
        this.setState({
            arrays : arrays
        })
    }

    render() {
        const { arrays } = this.state;
        console.log(arrays);
        console.log('arrays length: ' + arrays.length);

        const fArray = [];
        console.log(fArray);
        console.log('fArray length: ' + fArray.length);

        return (
            <div className='App'>
                {arrays.map(function(array) {                    
                    if (array.result === 'failed') {
                        const failed = {
                            fName: array.name,
                            fValue: array.value,
                            fResult: array.result
                        }
                        fArray.push(failed);
                    }
                    return null;
                })}
            </div>
        );
    }
}

export default App;

控制台结果:

enter image description here

在上图中为什么第一个arraysfArray显示0长度?

第二个arrays显示3个长度,fArray显示0,但它有两个失败的结果。

我的意思是,我可以从fArray得到两个失败的结果长度吗?

如果我的帖子重复,请告诉我。

1 个答案:

答案 0 :(得分:2)

当您console.log(fArray);时,您的fArray实际上是空的。结果为0.您填充fArray中的map。为什么不使用过滤功能

<div className='App'>
    {arrays.filter(a => a.result === 'failed').map(item => {
      // do what you want with failed items
    })}
</div>