【问题标题】:React - Conditional rendering ( iteration from multiple arrays )React - 条件渲染(来自多个数组的迭代)
【发布时间】:2019-10-06 03:10:40
【问题描述】:

大家好,目前我在 react 的条件渲染上遇到了问题。

我有 2 个数组保存在 state 中:

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

如果 arr_two 中的项目存在于 arr_one 中,我想用这些数组和条件渲染 div 迭代,然后渲染不同的 div。

注意:我不想用模数条件 (%) 来解决这个问题。

这是我的代码:

代码:

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>
        )
    }
}

输出:

我不在过滤器中! 1

我不在过滤器中! 2

我不在过滤器中! 3

我不在过滤器中! 4

我不在过滤器中! 5

预期输出:

项目 1

我不在过滤器中! 2

第 3 项

我不在过滤器中! 4

第 5 项

我也有我的代码演示 CodeSandBox

【问题讨论】:

    标签: javascript reactjs loops react-native iteration


    【解决方案1】:

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

    this.state.arr_two.includes(item)
    

    【讨论】:

    • 谢谢 aprill,这就是我想要的 ?抱歉问这个简单的问题,因为我还在迭代中学习 ?
    【解决方案2】:

    您将arr_one 的索引与arr_two 的值进行比较

    我不明白在你的 arr_one 值等于 0 但你的输出不是

    【讨论】:

    • 是的,已编辑。它实际上是保存在状态的数组?
    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 2020-06-13
    • 2021-02-22
    • 2019-07-22
    • 1970-01-01
    • 2021-03-23
    • 2018-09-10
    • 2018-07-21
    相关资源
    最近更新 更多