如何使用反应钩,检查道具并渲染适当的组件? (HOC)

时间:2020-04-14 11:11:48

标签: reactjs react-hooks react-hoc

最初,道具中没有属性国家。 因此,如果 props 中没有 country 属性,我需要显示加载消息,但问题在于,即使属性 country < / em>确实存在。因此 country 属性会在一段时间后出现,因此必须进行检查。我不确定这样做是否正确。

const loadingComponent = (WrappedComponent) => {
  return (props) => {
    const [loading, setLoading] = useState(true);

    useEffect(() => {
      if (props.country) return setLoading(false);
    }, [props]);

    return !loading ? <WrappedComponent {...props} /> : <p>Loading ...</p>;
  };
};

我试图避免使用类顺序组件。或任何其他方式来创建加载hoc?谢谢

1 个答案:

答案 0 :(得分:0)

在这种情况下,您实际上不需要状态。如果道具存在,则渲染该组件,如果不渲染,则渲染:

const loadingComponent = WrappedComponent =>
  props => 
    props.country ? 
      <WrappedComponent {...props} /> 
      : 
      <p>Loading ...</p>;

我将创建一个更通用的组件,该组件接受谓词以检查是否需要加载:

const loadingComponent = (predicate, WrappedComponent) =>
  props => 
    predicate(props) ? 
      <WrappedComponent {...props} /> 
      : 
      <p>Loading ...</p>;

然后您可以像这样使用它:

const Wrapped = (props => 'country' in props, ComponentX);

或检查其他事情

const Wrapped = (({ a }) => a < 5, ComponentY);