【问题标题】:How to put condition IF ELSE inside .map in React JS如何在 React JS 中的 .map 中放置条件 IF ELSE
【发布时间】:2020-01-09 01:25:58
【问题描述】:

我是 React Js 的新手。如果地图内的 ELSE 条件给了我错误。

我想将 IF ELSE 条件放在地图中。如果 IF ELSE 是可能的,我不想使用 三元运算符

class Home extends Component {

    constructor(props){
        //codes
    }

    testFunction = () => {
        //postDetails is something fetch from the server

        let tableDetail;
        tableDetail = Object.keys(postDetails).map((i) => (
            let val;

            /* I dont know how to achieve this part  */
            if(typeof postDetails[i].comment ===  'string'){
                val = <div>A String!</div>
            }else{
                val = <div>Not a string!</div>
            }
            /* I dont know how to achieve this part  */

            <>
                {val}
                // other codes ..
            </>;
        ));

        return tableDetail;
    }

    render() {

        return (
            <>
            <h3>Table</h3>
                {this.testFunction}
            </>
        )
    }

【问题讨论】:

标签: reactjs if-statement object-object-mapping


【解决方案1】:

另一个答案是缺少return,这在使用() 时是隐含的,但在使用{} 时需要明确说明:

testFunction = () => {
        //postDetails is something fetch from the server

        const tableDetail = Object.keys(postDetails).map((i) => {
            let val;

            if (typeof postDetails[i].comment === 'string') {
                val = <div>A String!</div>
            } else {
                val = <div>Not a string!</div>
            }

            return (<>
                {val}
                // other codes ..
            </>);
        });

        return tableDetail;
    }

【讨论】:

    【解决方案2】:

    更新你的testFunction
    testFunction = () => {
            //postDetails is something fetch from the server
    
            let tableDetail;
            tableDetail = Object.keys(postDetails).map((i) => {
                let val;
    
                /* I dont know how to achieve this part  */
                if(typeof postDetails[i].comment ===  'string'){
                    val = <div>A String!</div>
                }else{
                    val = <div>Not a string!</div>
                }
                /* I dont know how to achieve this part  */
    
                <>
                    {val}
                    // other codes ..
                </>;
            });
    
            return tableDetail;
        }
    

    【讨论】:

      猜你喜欢
      • 2022-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2022-12-12
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多