用打字稿反应:类型'never []'的参数不能分配给类型'StateProperties |的参数。 (()=> StateProperties)'

时间:2020-04-18 06:26:12

标签: reactjs typescript express react-tsx

我正在练习打字稿。对于后端,我使用节点表达打字稿,对于前端,我使用反应打字稿。我从后端获取了数据,然后尝试在浏览器上呈现它。我收到一个错误:property 'name' does not exist on type 'never'. TS2339。我认为此错误来自打字稿。这是错误visualization

这是我的后端设置

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;

1 个答案:

答案 0 :(得分:3)

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

state创建接口后,您需要提供该接口作为useState的泛型。

要解决第二个问题,您需要为key元素的每一项提供<li>道具

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>
  );

}