如何使用 React Hooks 检查道具并渲染正确的组件? (HOC)

How to use react hooks, to check props and render the proper component? (HOC)

最初,道具中没有属性 国家。 因此,如果 props 中没有 country 属性,我需要显示加载消息,但问题是它一直在继续渲染加载元素甚至 属性 country 确实存在。所以 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>;
  };
};

我试图避免使用 class 订单组件。或者有什么其他方法可以创建临时加载?谢谢

在这种情况下,您实际上不需要状态。如果 prop 存在渲染组件,如果不存在渲染加载:

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);