簡體   English   中英

與 Typescript 反應:“never[]”類型的參數不可分配給“StateProperties |”類型的參數 (() => 狀態屬性)'

[英]React with Typescript: Argument of type 'never[]' is not assignable to parameter of type 'StateProperties | (() => StateProperties)'

我正在練習 typescript。 對於后端,我使用 node express typescript,對於前端,我使用 react typeScript。 我從后端獲取數據並嘗試在我的瀏覽器上呈現它。 我收到一個錯誤: property 'name' does not exist on type 'never'. TS2339 property 'name' does not exist on type 'never'. TS2339 我認為這個錯誤來自 typescript。 這是錯誤可視化

這是我的后端設置

import express = require("express");
import cors = require("cors");
const app = express();
app.use(cors());
const port = 8080;
app.get("/", (req, res) =>
  res.send([
    {
      name: "John",
      age: 36
    },
    {
      name: "alex",
      age: 27
    }
  ])
);

app.listen(port, () => console.log(`server running port ${port}`));

這是我的 React 組件

    import React, { useEffect, useState } from "react";

interface StateProperties {
  name: string;
  age: number;
}

//StateProperties | (() => StateProperties)
function App() {
  const [state, setState] = useState<StateProperties>([]);

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    const response = await fetch("http://localhost:8080/");
    const data = await response.json();
    console.log(data);
    setState(data);
  };

  return (
    <div className="App">
      {state.length}

      {state.map((list, index) => {
        return <li key={index}>{list.name}</li>;
      })}
    </div>
  );
}

export default App;

您需要提供接口/類型別名,以便 TypeScript 知道state的類型。

在為state創建接口后,您需要為 useState 提供接口為useState

要解決第二個問題,您需要為<li>元素的每個項目提供key道具

interface StateProperties {
  name: string;
  age: number;
}

function App() {
  const [state, setState] = useState<StateProperties[]>([]);

  // do the rest

return (
  <div className="App">
    {state.map(({ name, age }) => {
      return <li key={`${name}-${age}`}>{name}</li>; //FROM HERE ERROR IS COMING
    })}
  </div>
  );

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM