import React, { useEffect } from 'react';
import { getRouteItem } from './utils';

/**
 * @TODO
 * @多种修正使用url判断异步处理这里防止回调执行的时候url变化导致一直执行
 * @每次执行先清除上一次的
 */

export const RenderRoute = React.memo(({ location, match, history, setRouteProps }) => {
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => setRouteProps(match, location, history), [location.pathname]);

  return null;
});

export const RenderComponents = React.memo(({ state, props }) => {
  const { match, history, location } = state;
  const { path, component, render, routes, ...other } = props;
  let Com, Ren;
  if (!routes) {
    Com = component;
    Ren = render;
  } else {
    const routeItem = getRouteItem(match, routes);
    Com = routeItem.component;
    Ren = routeItem.render;
  }
  return Com ? React.cloneElement(<Com />, { ...other, match, location, history }) : Ren({ ...other, match, location, history });
});
