TypeScript 中的 useParams 不允许解构 [英] useParams in TypeScript does not allow destructuring

查看:45
本文介绍了TypeScript 中的 useParams 不允许解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 但它有效.不确定,我的错误在哪里.你能看出那个错误吗?

解决方案

useParams 是通用的.您需要通过指定泛型的值来告诉打字稿您正在使用哪些参数,如下所示:useParams<MyParams>();在你的情况下是:

const { token } = useParams<{token?: string}>();

表示 token 要么是 string 要么是 undefined.

I was following this video ("JWTUser Sessions with ReactJS & GraphQL...") when at this time the guy destructures useParams() method from react-router-dom library.

In my case, that didn't work since I am getting this error:

This is the whole code at this point:

import React, { useState, useContext } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { useConfirmMutation } from '../gql/generated/graphql';
import { AppStateContext } from './provider';

export const Confirm: React.FC = () => {
    const history = useHistory();
    const { appSetAuthToken, appClearAuthToken, gqlError } = useContext(AppStateContext);

    const [show, setShow] = useState(false);
    const [email, setEmail] = useState('');
    const [confirm] = useConfirmMutation();
    const { token } = useParams();

    const handleFormSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            setShow(false);
            appSetAuthToken(token);
            const { data } = await confirm({ variables: email });
        } catch {

        }
    };

    if (token === undefined || token === '')
        return <div>Enlace de confirmación de usuario inválido</div>;

    return (
        <div>
            <div>Página de confirmación de usuario</div>
            {show ? <div>{gqlError.msg}</div> : undefined}
            <form>
                <div>
                    <input
                        value={email}
                        placeholder='Correo electrónico'
                        type='email'
                        onChange={e => { setEmail(e.target.value); }}
                    />
                </div>
                <button type='submit'>Confirmar</button>
            </form>
        </div>
    );
};

I have also tried the same on CodeSandbox but it works. Not sure, where is my mistake. Can you see that mistake?

解决方案

useParams is generic. You need to tell typescript which params you are using by specifying the value of the generic like this: useParams<MyParams>(); In your case it is:

const { token } = useParams<{token?: string}>();

Which says that token is either a string or undefined.

这篇关于TypeScript 中的 useParams 不允许解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆