【问题标题】:I have some error in the typescript and the hook of the useParam我的打字稿和 useParam 的钩子有一些错误
【发布时间】:2022-07-08 21:54:10
【问题描述】:

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)

这是我的代码


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 可能在此处未定义。试试client?.patch(pinId)

标签: reactjs typescript react-hooks react-router-dom


【解决方案1】:

在调用client.patch之前,您需要检查pinId是否未定义

【讨论】:

    【解决方案2】:

    我看到了两种解决方法:

    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(() => {
            fetchPinDetail(), // and here
              setComment('');
            setAddingComment(false);
          });
      }
    };
    
    1. 或者在外面处理这个addComment
    const { pinId } = useParams();
    
    if (!pinId) {
      throw new Error('Unexpected undefined pin id');
    }
    

    这里我抛出错误以确保pinId 将在addComment 中定义,但您可以以不同的方式处理。例如,您可以将用户重定向到另一个路由或在 JSX 中返回错误消息。

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 1970-01-01
      • 2021-01-03
      • 2021-02-14
      • 1970-01-01
      • 2020-11-22
      • 2021-08-12
      • 2019-01-24
      • 2023-03-08
      相关资源
      最近更新 更多