简体   繁体   中英

Switch case return multiple component

I loop on an object and I would like to display a result based on the Object.entries.

However the loop stops at the first return.

How can I get and display in one time what the components return to me? In a variable maybe ? Thanks

export const ResultItem: React.FC<Props> = (props:Props) => {
  const search = props
  
  const provideItem = () => {

  for (const [key, value] of Object.entries(search.result))
  {
    switch(key) {
      case "companies": 
        return <SearchCompany result={search.result[key]}/>
      case "medias":
        return <SearchMedias result={search.result[key]}/>
      case "contracts":
        return <SearchContracts result={search.result[key]}/>
      case "contacts":
        return <SearchContacts result={search.result[key]}/>
      }
    }
  }
  return (<div>{provideItem()}</div>)
}

Since you're returning a component, the execution of the for loop ends on the first iteration. An easy fix would be to create an array of items and push components into it, then render them at once.

 export const ResultItem: React.FC<Props> = (props:Props) => { const search = props const provideItem = () => { const items = [] for (const [key, value] of Object.entries(search.result)) { switch(key) { case "companies": items.push(<SearchCompany result={search.result[key]}/>) case "medias": items.push(<SearchMedias result={search.result[key]}/>) case "contracts": items.push(<SearchContracts result={search.result[key]}/>) case "contacts": items.push(<SearchContacts result={search.result[key]}/>) } } return items } return (<div>{provideItem()}</div>) }

You are getting only the first return because is that how a function works(first return "returns" that value and end the function), the return is for the function not for the "for" statement the return is ending the function.

You can use a map function to handle the component decision, and the return statement now can be used inside. This should work:

 const provideItem = () => {
        return Object.entries(search.result).map(seR => {
            const [key, value] = seR;
            switch (key) {
                case "companies":
                    return <SearchCompany result={value} />
                case "medias":
                    return <SearchMedias result={value} />
                case "contracts":
                    return <SearchContracts result={value} />
                case "contacts":
                    return <SearchContacts result={value} />
            }
        })
    }

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