我正在尝试将数据从父组件传递到子组件(对话框),但它认为它为 null 。数据来自api并根据id在父组件中渲染,当单击编辑按钮时,相同的数据将显示在对话框中的表单上。父级中显示错误 类型“null”不可分配给类型“{ id: number;”名称:字符串;电子邮件:字符串; } |未定义'.ts(2322) dialogBox.tsx(13, 3):预期的类型来自属性“postData”,该属性在“IntrinsicAttributes & DialogProps”类型上声明 在对话框中,此错误“postData”可能是“未定义”。ts(18048) 家长们
interface Post {
id: number;
name: string ;
email: string;
}
export default function ProfileBox2 () {
const [open, setOpen] = React.useState(false);
const [posts, setPosts] = useState<Post | null>(null);
const [error, setError] = useState<string | null>(null);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
if (!response.ok) {
throw new Error('Failed to fetch post');
}
const data: Post = await response.json();
setPosts(data);
} catch (error) {
if (typeof error === 'string') {
setError(error);
} else {
setError('An error occurred while fetching data');
}
}
};
fetchData();
}, []);
return (
<React.Fragment>
<div>
<h1>Profile</h1>
{error && <div>Error: {error}</div>}
{posts && (
<div>
<p>Name: {posts.name}</p>
<Divider/>
<p>Email: {posts.email}</p>
</div>
)}
<Button onClick={handleClickOpen}>Edit</Button>
<DialogBox isOpen={open} postData={posts}/>
</div>
</React.Fragment>
);
};
对话框(子)
interface DialogProps {
isOpen: boolean;
onClose?: () => void;
postData? : {
id: number;
name: string;
email: string;
};
}
const DialogBox: React.FC<DialogProps> = ({postData , isOpen, onClose}) => {
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<React.Fragment>
<Dialog
open={isOpen}
onClose={handleClose}
PaperProps={{
component: 'form',
onSubmit: (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const formJson = Object.fromEntries((formData as any).entries());
const email = formJson.email;
console.log(email);
handleClose();
},
}}
>
<DialogTitle>Dialog </DialogTitle>
<DialogContent>
<DialogContentText>
Edit Email address
</DialogContentText>
{/* {PostData && PostData.email && */}
<TextField
autoFocus
required
margin="dense"
id="name"
name="email"
label="Email Address"
type="email"
fullWidth
variant="standard"
value = {postData.email}
/>
{/* } */}
</DialogContent>
<DialogActions>
<Button type="submit">Edit</Button>
<Button onClick={handleClose}>Cancel</Button>
</DialogActions>
</Dialog>
</React.Fragment>
);
}
export default DialogBox;
注意事项:
postData? : {
id: number;
name: string;
email: string;
}
但是,由于
posts
的初始值为 null
,所以你违反了这一点。所以 TypeScript 会抱怨。
给定您的类型,其中
postData
可以是未定义的。以下内容将被破坏:value = {postData.email}
。这就是打字稿抱怨你的地方。
更新您的类型以允许
null
。
postData : {
id: number;
name: string;
email: string;
} | null
value = {postData?.email ?? ''}