简体   繁体   English

有什么办法可以让孩子不去评价?

[英]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.

相关问题 有没有更简洁的方法在 if 子句中进行如此多的比较? - Is there any cleaner way to make this amount of comparations in an if clause? 有什么办法可以制作<TabbedShowLayout>作为可编辑的视图? - Is there any way to make <TabbedShowLayout> as a editable view? 有什么办法可以使此反应组件更简洁? - is there any way to make this react component less verbose? 如何在本机反应中使任何子组件模糊? - How to make any child component blurred in react native? 有没有办法滚动到可排序树中的特定孩子? - Is there any way to scroll to a particular child in react sortable tree? 有什么办法知道子组件是否已经安装在React中 - Is there any way to know if a child component has mounted in React React Components 子组件渲染两次 - 有什么方法可以解决这个问题? - React Components child component render twice - any way to fix this? 有没有办法让父链接排除一些子元素? - Is there a way to make the parent Link exclude some child elements? 有没有办法在 react-native 样式组件中使用 nth-child 或:last-child? - Is there any way to use nth-child or :last-child in react-native styled components? 有没有办法确保子组件在父组件之后触发动作? - Is there a way to make sure child components fire actions after parent components?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM