简体   繁体   中英

React - Conditional rendering ( iteration from multiple arrays )

Hi guys currently I have a problem on conditional rendering in react.

I have 2 arrays saved in state :

this.state = {
   arr_one:[1,2,3,4,5],
   arr_two:[1,3,5]
};

I want to render divs iteration with those array and the condition if items in arr_two exists in arr_one, then render the differents divs.

note : I don't want to fix this with modulus condition (%).

Here's my code :

Code :

class TestComp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            arr_one:[1,2,3,4,5],
            arr_two:[1,3,5]
        };
    }


    render() {
        const filteredStyle={
            background:'red'
        }
        return (
            <div className="wrapper">
            {
                this.state.arr_one.map((item,index)=>
                    index === this.state.arr_two[index]?
                        <div key={index} className={filteredStyle}>
                            <p>Item {item}</p>
                        </div>
                    : 
                        <div key={index}>
                            <p>I'm not in filter! {item}</p>
                        </div>
                )               
            }

            </div>
        )
    }
}

Output :

I'm not in filter! 1

I'm not in filter! 2

I'm not in filter! 3

I'm not in filter! 4

I'm not in filter! 5

Expected Output :

Item 1

I'm not in filter! 2

Item 3

I'm not in filter! 4

Item 5

I also have my code demo in CodeSandBox

您可以使用includes修复条件index === this.state.arr_two[index]

this.state.arr_two.includes(item)

You are comparing index of arr_one with value of arr_two

And I don't understand during your arr_one have value equals 0 but your output isn't

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM