簡體   English   中英

我的打字稿和 useParam 的鈎子有一些錯誤

[英]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是否未定義

我看到兩種解決方法:

  1. 只需在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);
      });
  }
};
  1. 或者在addComment之外處理這個
const { pinId } = useParams();

if (!pinId) {
  throw new Error('Unexpected undefined pin id');
}

在這里,我拋出了錯誤以確保pinId將在addComment中定義,但您可以以不同的方式處理它。 例如,您可以將用戶重定向到另一個路由或在 JSX 中返回錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM