我在 TypeScript 中遇到了类型未知的问题
2022-10-27
399
这是我第一次使用 typescript,我遇到了名为“state”的变量的问题,因为它用于从 api 获取我的用户列表,但我收到此错误“'state' 类型为 'unknown'”,尽管它实际上有效。正如我所说,这是我第一次使用 typescript,如果它出现错误,我完全不明白它为什么会有效。
//React Imports
import React, { useEffect } from "react";
//MUI Imports
import Navbar from "../../Components/Navbar";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import { CardMedia } from "@mui/material";
import Typography from "@mui/material/Typography";
//Redux Imports
import { fetchAllUsers } from "../../redux/slices/users";
import { useDispatch, useSelector } from "react-redux";
function Users() {
const { list: users } = useSelector((state) => state.users);//Error in state.users
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchAllUsers() as any);
}, [dispatch]);
return (
<div className="Users">
<Navbar></Navbar>
<br></br>
<Box sx={{ flexGrow: 1 }}>
<Grid container spacing={2} alignItems="center" justifyContent="center">
{users.map((user, index) => (
<Grid item xs={3.1}>
<Card>
<CardMedia
component="img"
image={user.avatar}
alt="avatar image"
></CardMedia>
<CardContent>
<Typography gutterBottom variant="h5">
{user.first_name} {user.last_name}
</Typography>
<Typography gutterBottom variant="h6">
{user.email}
</Typography>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</Box>
</div>
);
}
export default Users;
2个回答
const { list: users } = useSelector((state:SPECIFYTYPEHERE) => state.users);//Error in state.users
您需要在 typescript 中的冒号后指定状态类型,否则状态将被推断为未知。
Daniel Smith
2022-10-27
您必须在此处包含状态的类型定义(您可能已在 Reducer 部分中编写),或者您可以使用条件链
state!.users
或
state!.users
,或者您可以将 any 作为状态的类型
(state:any)
Sharan Balakrishnan
2022-10-27