react-router4的Router内部可否嵌套其余元素?

答案是:不能?
一块儿来扒源码吧。html

let createRoute = basepath => element => {
  if (!element) {   // Router的子元素
    return null; 
  }

  if (element.type === React.Fragment && element.props.children) {      // 处理Fragment类型元素包裹的Route(简写:<></>)
    return React.Children.map(element.props.children, createRoute(basepath));
  }
  invariant(
    element.props.path || element.props.default || element.type === Redirect,
    `<Router>: Children of <Router> must have a \`path\` or \`default\` prop, or be a \`<Redirect>\`. None found on element type \`${
      element.type
    }\``
  );

  invariant(
    !(element.type === Redirect && (!element.props.from || !element.props.to)),
    `<Redirect from="${element.props.from}" to="${
      element.props.to
    }"/> requires both "from" and "to" props when inside a <Router>.`
  );

  invariant(
    !(
      element.type === Redirect &&
      !validateRedirect(element.props.from, element.props.to)
    ),
    `<Redirect from="${element.props.from} to="${
      element.props.to
    }"/> has mismatched dynamic segments, ensure both paths have the exact same dynamic segments.`
  );
    // 如下处理 Redirect元素
  if (element.props.default) {
    return { value: element, default: true };
  }

  let elementPath =
    element.type === Redirect ? element.props.from : element.props.path;

  let path =
    elementPath === "/"
      ? basepath
      : `${stripSlashes(basepath)}/${stripSlashes(elementPath)}`;

  return {
    value: element,
    default: element.props.default, 
    path: element.props.children ? `${stripSlashes(path)}/*` : path
  };
};

除了 Fragment,Route,Redirect和其余内部约定的包含default属性的内部路由组件,其余html标签是不能生成正确的路由配置的。
So,若是你用了其余标签包裹Router子组件,页面对路由是不能正确响应的。ide

相关文章
相关标签/搜索