[英]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但这给出了 api-data 是未定义的
<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.如果您不想这样做,您可能必须重新研究渲染组件的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.