programing

타이프 스크립트의 소품으로 useState 전달

fastcode 2023. 3. 26. 11:50
반응형

타이프 스크립트의 소품으로 useState 전달

두 개의 자식 구성 요소를 가진 부모 구성 요소가 있다고 가정합니다.

const Parent = () => {
   const [myVar, setmyVar] = useState(false)

   return (
     <>
       <MyChildComponent1 myVar={myVar} setMyVar={setMyVar} \> 
       <MyChildComponent2 myVar={myVar} \>
     </>
   )
}

여기서 타입을 올바르게 설정하려면 어떻게 해야 합니까?MyChildComponent2?

지금까지 생각해낸 것은 다음과 같습니다.

const MyChildComponent1 = (
  {myVar, setMyVar}: 
  {myVar: boolean, setMyVar: (value: boolean) => void}) = (...)

의 타입입니까?setMyvar맞습니까?아니면 다른 걸 해야 하나요?

호출에서 반환된 함수와 일치하는 유형useState다음과 같습니다.

setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void;

의 타입 정의 파일을 참조하면,DefinitelyTyped[1], 반환 유형의 두 번째 유형은 디스패치임을 알 수 있습니다.

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

따라서 제공된 범용 유형은 다음 주소로 전달됩니다.SetStateAction<S>다음과 같이 정의됩니다.

type SetStateAction<S> = S | ((prevState: S) => S);

따라서 기본적으로 컴포넌트의 인터페이스는 다음과 같습니다.

interface IProps {
  myVar: boolean;
  setMyVar?: (value: boolean | (prevVar: boolean) => boolean) => void;
}

@Retsam이 말했듯이 React에서 내보낸 유형을 사용하는 것이 가장 좋습니다.

import { Dispatch, SetStateAction } from "react";

interface IProps {
  myVar: boolean;
  setMyVar?: Dispatch<SetStateAction<boolean>>;
}

자료: [1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L845

디스패치 및 SetStateAction 유형

@Retsam에서 언급했듯이 유형을 Import하여 사용할 수도 있습니다.Dispatch그리고.SetStateAction반응에서:

import React, { Dispatch, SetStateAction } from 'react';

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatch<SetStateAction<boolean>>
) => {...};

보너스

이것을 자주 사용하고 있는 자신을 발견하면, 읽기 쉽도록 타입 에일리어스를 작성합니다.

import React, { Dispatch, SetStateAction } from 'react';

type Dispatcher<S> = Dispatch<SetStateAction<S>>;

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatcher<boolean>,
) => {...};

이게 도움이 되길 바라

@fiz의 코멘트에 덧붙여, 그의 블록 코드는 나에게 조금 효과가 없었습니다.

import React, { Dispatch, SetStateAction } from 'react';

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatch<SetStateAction<<boolean>>
) => {...};

나는 설정해야 했다.setMyVar: Dispatch<SetStateAction<boolean>>(브래킷이 하나 너무 많았습니다.

Interface 및 React 컴포넌트를 사용하여 이와 같이 할 수도 있습니다.

Main Component.tsx

메인에서 정의된 useState 컴포넌트의 값 할당은 하위 컴포넌트에서 이루어집니다.이 필드가 트리거되면 useEffect의 코드가 실행됩니다.

import React, { useEffect } from 'react';
import Login from './views/Login/index';

const App: React.FunctionComponent = () => {
    const [isAuthenticated, setAuthenticatedStatus] = React.useState(false);

    useEffect(() => {
        if (isAuthenticated)
            window.location.href = "<redirect url>";
    }, [isAuthenticated]);

    return (<Login setLoginStatus={setAuthenticatedStatus} />)
};

export default App;

Child Component.tsx

import { Dispatch, SetStateAction, FunctionComponent } from 'react';
import authService from '../../apiServices/authService';

interface IProps {
   setLoginStatus: Dispatch<SetStateAction<boolean>>;
}

const Login: FunctionComponent<IProps> = (props: IProps) => {

   const login = async (username: string, password: string) => {
      const response = await authService.authenticateUser(username, password);

      if (response && response.statusCode == 200 && response.result.accessToken) {
         props.setLoginStatus(true);
      }
      else {
         // ...
      }
   };


   return (
      <>
         ...
      </>
   );
};

export default Login;

다른 답변은 약간 혼란스러웠기 때문에 다음과 같이 대응했습니다.

parent.ts의 useState()를 인스턴스화합니다.

const [someState, setSomeState] = useState<stateType>(initialState)

setSomeState()를 child.ts에 전달합니다.

<Child
    setSomeState={setSomeState}
/>

() 없이 이름만 전달해 주세요.

in child.ts는 다음과 같이 Propos를 설정합니다.

import Dispatch from 'react'

interface Props {setSomeState: Dispatch<stateType>}

My Child Component 1.tsx
set type Proposs는 다음과 같이 설정합니다.

'react'에서 반응 가져오기

소품 = {
myVar: boolean;
setmyVar: 반응합니다.디스패치 <응답하세요.SetStateAction<boolean> >;
}
Const MyChildComponent =({myVar, setmyVar: 소품) => {

...고객님의 코드...


}

언급URL : https://stackoverflow.com/questions/56028635/passing-usestate-as-props-in-typescript

반응형