如何在React JS中将条件IF ELSE放在.map中

时间:2019-09-06 07:17:33

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

我是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}
            </>
        )
    }

2 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:0)

另一个答案缺少使用 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;
    }