import invariant from '../utils/invariant';
/**
* Make sure the config passed e.g. to StackRouter, TabRouter has
* the correct format, and throw a clear error if it doesn't.
*
* 检查传递给StackRouter, TabRouter等路由器的路由配置的格式,如果有问题直接抛出错误。
* 什么样的路由配置认为是没问题的 ?
* 1. 必须有配置项
* 2. 每个配置项必须包含屏幕组件,也就是属性 screen 或者 属性方法 getScreen
* 3. 每个配置项中 screen 或者 getScreen 二者最多存在一个,不能两个同时设置
* 4. 如果是属性 screen, 其类型必须是 string 或者 function
*/
function validateRouteConfigMap(routeConfigs) {
const routeNames = Object.keys(routeConfigs);
// 断言 : 必须有配置项
invariant(
routeNames.length > 0,
'Please specify at least one route when configuring a navigator.'
);
routeNames.forEach(routeName => {
const routeConfig = routeConfigs[routeName];
const screenComponent = getScreenComponent(routeConfig);
if (
!screenComponent ||
(typeof screenComponent !== 'function' &&
typeof screenComponent !== 'string' &&
!routeConfig.getScreen)
) {
// 如果某个配置项有 screen 属性,但 screen 属性的值不是一个 function 或者 string,
// 抛出错误
throw new Error(
`The component for route '${routeName}' must be a ` +
'React component. For example:\n\n' +
"import MyScreen from './MyScreen';\n" +
'...\n' +
`${routeName}: MyScreen,\n` +
'}\n\n' +
'You can also use a navigator:\n\n' +
"import MyNavigator from './MyNavigator';\n" +
'...\n' +
`${routeName}: MyNavigator,\n` +
'}'
);
}
if (routeConfig.screen && routeConfig.getScreen) {
// 如果某个配置项的 screen 和 getScreen 同时存在,抛出错误
throw new Error(
`Route '${routeName}' should declare a screen or ` +
'a getScreen, not both.'
);
}
});
}
function getScreenComponent(routeConfig) {
if (!routeConfig) {
return null;
}
return routeConfig.screen ? routeConfig.screen : routeConfig;
}
export default validateRouteConfigMap;
React Navigation源代码阅读 :routers/validateRouteConfigMap.js
猜你喜欢
转载自blog.csdn.net/andy_zhang2007/article/details/80296954
今日推荐
周排行