useParam returns string | undefined, but the function requires a string | MutationSelection. I have error 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)
.
here is my code
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)
})
}
}
client is object from sanity.io
您需要在调用client.patch
之前检查pinId
是否未定义
I see two way of fixing this:
if
condition in addComment
functionconst 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');
}
Here I've thrown and error to ensure that pinId
will be defined in addComment
but you can handle this differently. For instance you could redirect user to another route or return an error message in JSX.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.