[英]I have some error in the typescript and the hook of the useParam
useParam 返回字符串 | 未定義,但該函數需要一個字符串 | 突變選擇。 我有錯誤An argument of type "string | undefined" cannot be assigned to a parameter of type "string | MutationSelection". The type "undefined" cannot be assigned to the type "string | MutationSelection".ts(2345)
An argument of type "string | undefined" cannot be assigned to a parameter of type "string | MutationSelection". The type "undefined" cannot be assigned to the type "string | MutationSelection".ts(2345)
。
這是我的代碼
const PinDetail: React.FC<PropsType> = ({ user }) => {
const { pinId } = useParams()
const addComment = () => {
client.patch(pinId) //here error
.setIfMissing({ comments: [] })
.insert('after', 'comments[-1]', [{
comment,
_key: uuidv4(),
postedBy: {
_type: 'postedBy',
_ref: user._id
}
}])
.commit()
.then(() => {
fetchPinDetail(), // and here
setComment('')
setAddingComment(false)
})
}
}
客戶端是來自 sanity.io 的對象
您需要在調用client.patch
之前檢查pinId
是否未定義
我看到兩種解決方法:
addComment
函數中添加一個if
條件const addComment = () => {
if (pinId) {
client
.patch(pinId)
.setIfMissing({ comments: [] })
.insert('after', 'comments[-1]', [
{
comment,
_key: uuidv4(),
postedBy: {
_type: 'postedBy',
_ref: user._id,
},
},
])
.commit()
.then(() => {
// line ended by , instead of ;
fetchPinDetail();
setComment('');
setAddingComment(false);
});
}
};
addComment
之外處理這個const { pinId } = useParams();
if (!pinId) {
throw new Error('Unexpected undefined pin id');
}
在這里,我拋出了錯誤以確保pinId
將在addComment
中定義,但您可以以不同的方式處理它。 例如,您可以將用戶重定向到另一個路由或在 JSX 中返回錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.