简体   繁体   中英

What's an efficient way to render child items of one of many list items in React?

I have a component that renders a few list items, and some of those may contain another set of child items inside of a <ul> tag when the parent list item is clicked.

This is a rather large dataset so what would be an efficient way to render (and destroy on second click) the child items when the parent list item is clicked?

Example code below:

const Timeline = ({ edges }) => {

    const getChildren = async id => {
        
    }

    return (
        <ul className={styles.timeline}>
            {edges.sort((a, b) => formatDate(a.node.date) - formatDate(b.node.date)).map(({ node }, index) => (
                <li key={node.id} className="timeline-item">
                    {!node.children.edges.length > 0 ? (
                        <a className="timeline-item-link" onClick={() => getChildren(node.id)}>
                            <h2 className="timeline-item-title">{node.title}</h2>
                        </a>
                        <ul className="timeline-children"></ul>
                    ) : null}
                </li>
            ))}
        </ul>
    )

}

Any help would be really appreciated!

The big thing is you're going to want to make each of the parent elements their own component. Otherwise react needs to rerender the whole list anytime anything changes. Something like:

const Timeline = ({ edges }) => {
    return (
        <ul className={styles.timeline}>
            {edges.sort((a, b) => formatDate(a.node.date) - formatDate(b.node.date)).map(({ node }, index) => (
                <TimelineChild node={node} key={index} />
            ))}
        </ul>
    )
}


const TimelineChild = ({ node }) => {
    const getChildren = async id => {
        
    }
    
    return (<li key={node.id} className="timeline-item">
                    {!node.children.edges.length > 0 ? (
                        <a className="timeline-item-link" onClick={() => getChildren(node.id)}>
                            <h2 className="timeline-item-title">{node.title}</h2>
                        </a>
                        <ul className="timeline-children"></ul>
                    ) : null}
                </li>);
}

You may also want to give all the node.children their own component, too.

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