react-router4的Router內部能否嵌套其他元素?

答案是:不能?
一起來扒源碼吧。


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子組件,頁面對路由是不能正確響應的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章