React Native中如何判断route不为空再获取路由参数?
解决React Native中route为空的判断问题
在类组件里获取route和fromPage时,为了避免route或route.params为空导致报错,可以通过以下几种方式做安全处理:
方式一:使用可选链操作符(ES2020+)
这是最简洁的写法,能自动处理空值情况,不会抛出错误:
const { route } = this.props; const fromPage = route?.params?.fromPage;
如果route或route.params为空,fromPage会自动变成undefined,你还可以给它设置默认值:
const fromPage = route?.params?.fromPage || 'defaultPage';
方式二:传统条件判断
如果项目环境不支持可选链,就用常规的if判断或三元表达式:
const { route } = this.props; let fromPage = 'defaultPage'; if (route && route.params) { fromPage = route.params.fromPage; }
或者更紧凑的三元写法:
const { route } = this.props; const fromPage = route && route.params ? route.params.fromPage : 'defaultPage';
方式三:解构时设置默认兜底
在解构props和params时直接设置默认空对象,避免后续解构报错:
const { route = {} } = this.props; const { fromPage = 'defaultPage' } = route.params || {};
内容的提问来源于stack exchange,提问作者Mahdi
相关产品推荐
相关产品推荐

