在 React Native(JavaScript/TypeScript)中,当你访问一个可能为 null 或 undefined 的对象属性时,如果没有使用可选链(?.)或者进行安全检查,可能会导致运行时错误,阻断后续代码的执行。
为什么会阻断后续语句?
当你试图访问一个 null 或 undefined 的属性时,JavaScript 会抛出一个错误,例如:
javascript
复制
TypeError: Cannot read properties of null (reading 'name')
一旦发生此错误,脚本的执行会停止,并不会继续执行后续代码。
示例代码
没有处理 null 的情况:
javascript
复制
const obj = null;
console.log(obj.name); // TypeError: Cannot read properties of null (reading 'name')
console.log("这句不会执行");
正确的写法:
使用可选链 ?.:
javascript
复制
const obj = null;
console.log(obj?.name); // undefined
console.log("这句会执行");
手动检查 null 或 undefined:
javascript
复制
const obj = null;
if (obj && obj.name) {
console.log(obj.name);
}
console.log("这句会执行");
为什么使用 ?. 是推荐的?
更简洁:避免手动 if 检查。
避免错误:不会因访问 null 或 undefined 的属性而导致崩溃。
可读性更高:代码更直观。
在 TypeScript 中的额外好处
如果你使用 TypeScript,开启严格模式(strict 或 strictNullChecks),会在编译时提示哪些对象可能为 null 或 undefined,从而帮助你在开发时规避错误。
示例
typescript
复制
type User = { name: string } | null;
const user: User = null;
// 编译错误:Object is possibly 'null'.
console.log(user.name);
// 使用可选链避免错误:
console.log(user?.name); // 输出:undefined
结论
在 React Native 项目中,始终检查对象是否为 null 或 undefined 是个好习惯。推荐使用可选链(?.)语法来处理可能为 null 的对象,从而保证代码的健壮性和可读性。