简体   繁体   中英

Is there any way to make child not to evaluate?

Sorry if this is dumb but I got a spinner-wrapper which looks like this.

type Props = { condition: boolean; children: React.ReactNode };

export const SpinnerWrapper = ({ condition, children }: Props) => {
  return condition ? <Spinner /> : <>{children}</>;
};

But children evaluates nevertheless of the condition. So if it's loading child will give undefined error. Any way to prevent this? I want to abstract the conditional rendering.

EDIT: conditional rendering works fine without the wrapper, like this

{isLoading ? (
        <Spinner />
      ) : (<> {some.api.data} </> )

But this gives api-data is undefined

<SpinnerWrapper condition={isLoading}>{some.api.data}</SpinnerWrapper>

This is happening because your children are evaluated in the parent Component in this manner:

<SpinnerWrapper>
    <children1 />
    <children2 />
    ...
</SpinnerWrapper>

Instead, you want to conditionally show the spinner with no children when it's loading and with children when it's not.

isLoading ?
    <SpinnerWrapper /> : 
    <SpinnerWrapper>
        <children1 />
        <children2 />
        ...
    </SpinnerWrapper>

If you do not want to do this, you probably have to re-study the way you are rendering your components.

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