即使组件仍假定要渲染,React道具也会被评估

时间:2018-06-29 18:10:30

标签: reactjs react-context

我为我的组件提供了一个包装器,告诉他们在完成如下所示的加载之前不要渲染

import React from 'react';
import LoadingSpinner from 'vivid.react.components/atoms/LoadingSpinner';

class Wrapper extends React.Component {
    componentDidMount() {
        this.props.getInitialState();
    }

    render() {
        const { error, isLoadingInitialState } = this.props;
        return (
            <div className='wrapper'>
                {!!error && <div>Error: {error.message}</div>}
                {isLoadingInitialState
                    ? <LoadingSpinner/>
                    :  children
                }
            </div>
        )
    }
};

export default Wrapper;

但是,当我在Context Consumer中使用此包装时,即使LoadingInitialState为true并且不应该渲染子级,也仍在评估子级的道具。

const Screen = () => {
    <div>
     <Context.Consumer>
      {(context) => {
          <Wrapper isLoadingInitialState={context.isLoadingInitialState} getInitialState={context.getInitialState)>
            <ChildComponent price = {context.data.props}/> // throws an error because data is undefined
          </Wrapper>
      }}
    </Context.Context>
}

任何人都可以解释为什么ChildComponents道具即使在未呈现的情况下仍在被撤离吗?有更好的解决方案吗?

0 个答案:

没有答案