【问题标题】:"Property does not exist on type 'never'" when i try to access a json data from API response当我尝试从 API 响应访问 json 数据时,“属性不存在于类型‘从不’上”
【发布时间】:2021-05-30 08:56:00
【问题描述】:

当我尝试访问idtitleitems 字段时,它显示属性不存在于类型“从不”

顺便说一句,使用console.log(response.data) 记录数据时,我可以正确查看数据。我遵循了一个教程,它在教程中运行良好。

const [items, setItems] = useState([]);

    useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/posts")
            .then(response => {
                setItems(response.data);
            })
            .catch(error => { console.log(error) })
    });

{items.map((item) => {
     <li key={item.id}>{item.title}</li>
})}

【问题讨论】:

  • 数据来自Resources部分的JSONPlaceholder,它是一个json。
  • 您的代码存在一些问题,但我认为它们中的任何一个都不会导致您遇到错误。你能发布你正在使用的类型定义的整个组件吗?

标签: reactjs typescript axios


【解决方案1】:

您需要为items 提供一个接口/类型:

interface Item {
  id: number
  title: string
}
const [items, setItems] = useState<Item[]>([]);

// OR

const [items, setItems] = useState<any[]>([]); // Do this if you don't want to write an interface or type

useState 接受generic 并返回有状态的值(提供的type)和一个函数(接受相同的type)来更新状态价值。

当我们不为useState 提供任何泛型时,它返回函数,但类型为never

这就是您看到错误的原因:

属性(id 和标题)在 never 类型上不存在

【讨论】:

  • 非常感谢!!!有效。感谢您的所有编辑,这是我在这里的第一篇文章,所以我不知道如何正确编写它。我会提高我的知识,我希望我能像你一样在未来帮助别人。祝你有美好的一天!!!!
  • 欢迎您!很高兴编辑和回答:) 是的,你可以帮助其他人和 StackOverflow 社区。祝你有美好的一天!
猜你喜欢
  • 2022-06-13
  • 2023-03-10
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
相关资源
最近更新 更多