react 如何判断空
判断空值的常见方法
在React中判断变量是否为空值(如null、undefined或空字符串"")可以通过以下方式实现:
严格等于检查
if (value === null || value === undefined) {
// 处理空值
}
宽松等于检查
if (value == null) {
// 同时覆盖null和undefined
}
空字符串检查
if (value === "") {
// 处理空字符串
}
使用逻辑运算符
可选链操作符(?.)

const nestedValue = obj?.prop?.nestedProp;
// 如果obj或prop为null/undefined,返回undefined
空值合并运算符(??)
const displayValue = inputValue ?? "default";
// 仅在inputValue为null/undefined时使用默认值
数组或对象的空值判断
检查空数组
if (Array.isArray(arr) && arr.length === 0) {
// 处理空数组
}
检查空对象

if (Object.keys(obj).length === 0) {
// 处理空对象
}
React组件中的空值处理
条件渲染
{data && <Component data={data} />}
默认值propTypes
Component.propTypes = {
optionalValue: PropTypes.string
};
Component.defaultProps = {
optionalValue: ""
};
TypeScript中的空值检查
类型守卫
function isNotNull<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
const filteredArray = array.filter(isNotNull);
非空断言运算符
const definitelyExists = maybeExists!;
// 仅在确定不为空时使用






