简体   繁体   中英

I have some error in the typescript and the hook of the useParam

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:

  1. Simply add an if condition in addComment function
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);
      });
  }
};
  1. Or handle this outside 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM