React+TypeScript报Property 'strDrink' does not exist on type 'string'如何解决?
问题原因
你报错的核心是TypeScript类型推导不匹配:
初始化useState时传入了空字符串"",TS会自动推导recipe的类型为string;但你后续调用setCurrentRecipe传入的是对象类型的cocktail,类型不匹配,所以会提示string类型上不存在strDrink属性。
解决步骤
- 第一步:先定义你的cocktail对象的类型,把你需要用到的属性都声明清楚,示例如下:
// 可以根据你实际的cocktail结构补充所有属性 interface Cocktail { strDrink: string; // 其他属性例如:strInstructions?: string; 等 }
如果暂时不想写全所有属性,也可以先用type Cocktail = Record<string, any>过渡,但不推荐长期使用。
- 第二步:给useState指定泛型,替换错误的初始值:
原来的空字符串初始值不符合对象类型,我们可以把初始值设为null,同时给useState加上泛型声明:
// 声明recipe的类型可以是 Cocktail 或者 null const [recipe, setCurrentRecipe] = useState<Cocktail | null>(null);
- 第三步:访问属性时增加空值判断,避免初始状态下的运行时报错:
你可以用可选链运算符直接访问,也可以加条件渲染:
{/* 方案1:可选链,配合空值合并运算符设置默认值,避免显示undefined */} <DrawerHeader>recipe of {recipe?.strDrink ?? ''}</DrawerHeader> {/* 方案2:条件渲染,只有recipe存在时才展示内容 */} {recipe && <DrawerHeader>recipe of {recipe.strDrink}</DrawerHeader>}
内容的提问来源于stack exchange,提问作者Denis
相关产品推荐
相关产品推荐

