简体   繁体   English

类型“{}[]”上不存在属性“_id”

[英]Property '_id' does not exist on type '{}[]'

I'm c native and I'm studying JS, TS, ReactJs. I created an application for study purposes, I am sending from the backend a package like:我是 c 本地人,我正在学习 JS,TS,ReactJs。我创建了一个用于学习目的的应用程序,我从后端发送一个 package,例如:

{_id: '624d9476a390104449255c45', email: 'JohnSpecial@gmail.com', username: 'JohnSpecial', userpass: '12345', __v: 0}. 

In my frontend I use react and ts.在我的前端,我使用 react 和 ts。 The app is very simple: I use fetch to make requests to the backend.该应用程序非常简单:我使用 fetch 向后端发出请求。 This is my code:这是我的代码:

import { useEffect, useState } from 'react'

export const App = () => {
  const [backendData, setbackendData] = useState([{}])

  useEffect(() => {
    fetch('/readData/12345')
      .then((response) => response.json())
      .then((data) => {
        console.log('Data Received ' + JSON.stringify(data[0]))
        var myArr = JSON.parse(JSON.stringify(data[0]))
        console.log(myArr)
        setbackendData(myArr)
      })
  }, [])

  return (
    <div className="App">
      Mongodb React Typescript - Send Data
      <p></p>
      {typeof backendData._id === 'undefined' ? <p>Loading...</p> : backendData._id}
    </div>
  )
}

I was using react and javascript and it was working.我正在使用 React 和 javascript 并且它正在工作。 When I started using TS it started to look like this error message: Property '_id' does not exist on type '{}[]'.当我开始使用 TS 时,它开始看起来像这样的错误消息:属性“_id”在类型“{}[]”上不存在。

How can I show this JSON on my browser?如何在我的浏览器上显示这个 JSON?

Thanks谢谢

You'll need to tell typescript what type of data will be stored in the useState hook.您需要告诉 typescript 什么类型的数据将存储在useState挂钩中。

import { useEffect, useState } from 'react'

interface BackendData {
  _id: number;
}

export const App = () => {
  const [backendData, setbackendData] = useState<BackendData | null>(null)

  useEffect(() => {
    fetch('/readData/12345')
      .then((response) => response.json())
      .then((data) => {
        setbackendData(data[0] as BackendData)
      })
  }, [])

  return (
    <div className="App">
      Mongodb React Typescript - Send Data
      <p></p>
      {backendData ? backendData._id : <p>Loading...</p>}
    </div>
  )
}

playground 操场

Your backendData has type {}[] .您的backendData类型为{}[] You need to properly type it.您需要正确输入它。 Example:例子:

interface BackendData {
  _id: number;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM