React+Next.js中出现"Property 'title' does not exist on type 'string'"错误如何修复?
修复React+Next.js中"Property 'title' does not exist on type 'string'"错误
问题根源
你给useState设置的初始值是空字符串'',TypeScript会自动推断data的类型为string,但后续通过setData传入的是接口返回的对象(包含title属性),类型不匹配导致报错。
修复方案
方式一:明确指定类型(推荐)
先定义接口描述返回数据的结构,给useState指定该类型,同时设置正确的初始值(null或undefined),让TypeScript能正确识别数据类型:
import { useEffect, useState } from "react" // 定义接口匹配接口返回的数据结构 interface Todo { id: number; title: string; completed: boolean; } export default function Test() { // 指定data的类型为Todo或null,初始值设为null const [data, setData] = useState<Todo | null>(null) useEffect(() => { const callData = async () => { const res = await fetch('https://jsonplaceholder.typicode.com/todos/10') const fetchedData = await res.json() setData(fetchedData) } callData() }, []) return ( data === null ? <>loading ... </> : <div>{data.title}</div> ) }
方式二:临时使用类型断言(不推荐长期用)
如果不想定义接口,可通过unknown类型配合类型断言临时解决,但会丢失TypeScript的类型校验能力:
import { useEffect, useState } from "react" export default function Test() { const [data, setData] = useState<unknown>(null) useEffect(() => { const callData = async () => { const res = await fetch('https://jsonplaceholder.typicode.com/todos/10') const fetchedData = await res.json() setData(fetchedData) } callData() }, []) return ( data === null ? <>loading ... </> : <div>{(data as {title: string}).title}</div> ) }
额外优化
- 将
fetch的链式调用改为async/await形式,代码更易读; - 增加错误处理,避免请求失败导致的异常:
useEffect(() => { const callData = async () => { try { const res = await fetch('https://jsonplaceholder.typicode.com/todos/10') if (!res.ok) throw new Error('请求失败') const fetchedData = await res.json() setData(fetchedData) } catch (err) { console.error('获取数据出错:', err) } } callData() }, [])
内容的提问来源于stack exchange,提问作者Jennie
相关产品推荐
相关产品推荐

