简体   繁体   中英

React JS: ForEach Function isn't returning anything

I have a JS function in my code that is supposed to return a React Component for Each element of my split string, but for some reason, when I call it on my main "return()", the function isn't returning anything. I tried to put the function directly inside of the return(), but the same happened. That never happened to me before and I have no idea of what it is.

Here is my code:

import React from 'react';

import DatabaseLiLine from './DatabaseLiLine';

const DatabaseLiSection = ({ className, children, classId }) => {
    const example = "Use,This,As,An,Example";
    const splitLiTitles = example.split(",");

    const returnLines = () => {
        splitLiTitles.forEach(element => {
            return(
                <DatabaseLiLine>
                    {element}
                </DatabaseLiLine>
            );
        })
    }
    return (
        <li className={className}>
            <a href="/">{children}</a>
            <div id={classId} className="consult_box">
                {returnLines()}
            </div>
        </li>
    );
}

export default DatabaseLiSection;

forEach doesn't return anything. Change your code to use map method.

    const returnLines = () => {
        splitLiTitles.map(element => {
            return(
                <DatabaseLiLine>
                    {element}
                </DatabaseLiLine>
            );
        })
    }

Having a little brain fart here but I forget if you also need to return the map method, like adding return before splitLiTitles.map... . I think it should work without it, but if it doesn't try adding that return in front as well.

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