reactjs - 与 Typescript 反应:“never[]”类型的参数不可分配给“StateProperties |”类型的参数 (() => 状态属性)'
问题描述
我正在练习打字稿。对于后端,我使用 node express typescript,对于前端,我使用 react typeScript。我从后端获取数据并尝试在我的浏览器上呈现它。我收到一个错误:property 'name' does not exist on type 'never'. TS2339
。我认为这个错误来自打字稿。这是错误可视化
这是我的后端设置
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
。
要解决第二个问题,您需要为元素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>
);
}
推荐阅读
- node.js - 节点 - 限制作为虚拟对象发回的数据
- r - 如何在 R 中执行引导到诊断测试?
- javascript - 选择没有最后一个空格的潜水文本
- slider - 如何将多个自动轮播添加到我的页面?
- android - 如何从 Android PIE 访问 HTTP JSON 响应
- algorithm - 使用 ElasticSearch 进行模糊重复搜索
- oracle-apex - 从其他 Web 应用程序打开公共 oracle apex 页面
- c# - 如何将 JSON 嵌套对象数组反序列化为 c# 对象
- java - 在内存中,iText .PDF 正在生成奇怪的字符
- android - React Navigation 选项卡导航导航在 Android 上不起作用(在 iOS 上工作正常)