새로운 업데이트에 반응하세요

PHPz
풀어 주다: 2024-07-29 13:15:50
원래의
747명이 탐색했습니다.

React  The new updates

이번 주에는 새로운 React 19 업데이트와 Hooks에 대해 이야기하겠습니다. 이러한 새로운 업데이트 중 일부를 살펴보고 사용해 본 결과 개발자가 앱, 특히 대화형 양식 관련 애플리케이션을 구축할 때 수행하는 엄격한 활동 중 일부가 단순화되었다는 점에만 동의할 수 있습니다.

저와 함께 새로운 업데이트를 살펴보세요.

React 컴파일러: React 컴파일러는 React 코드를 선택하여 브라우저용 JavaScript 코드로 변환하고 구성 요소 또는 사용자 인터페이스의 상태를 관리합니다. 이 단일 작업은 애플리케이션 성능을 최적화하는 데 도움이 됩니다.

useMemo 후크, useCallback 후크 및 React.Memo에 익숙하다면 구성 요소를 메모(나중에 사용할 수 있도록 값 또는 함수 저장)하는 데 도움이 되므로 다시 작업할 필요가 없다는 점을 이해할 것입니다. 상태 변경이 없을 때 렌더링됩니다. 상태가 변경되면 React는 문제의 구성 요소와 해당 하위 구성 요소를 다시 렌더링하고, 코드에 변경 사항이 없으면 구성 요소는 구성 요소의 이전 메모리, 값 및 상태를 그대로 유지하거나 향후를 위한 후크를 유지합니다. 용도; 이를 통해 구성 요소의 성능을 최적화합니다. 이는 앞서 언급한 후크를 수동으로 호출할 필요 없이 React Compiler가 자동으로 수행하는 작업입니다.

Form Actions: React를 사용하는 가장 큰 장점 중 하나는 상태 관리 및 변경이며, 이는 대부분 을 사용할 때 발생합니다. 요소. 양식은 사용자 상호 작용을 보다 효과적으로 생성하고 처리하는 데 도움이 됩니다.

form actions를 사용하면 데이터의 실시간 변형을 적용하기 위해 onSubmit 및 onChange와 같은 이벤트 핸들러가 필요하지 않으며 대신 action prop을 전달할 수 있습니다. 이벤트를 트리거하는 함수를 수신하는

요소에
const myFunction = async (formData) => {
  const [name, setName] = useState("")

  const updatedName = await nameChange(formData.get("name"))
     setName(updatedName)
}

<form action={myFunction}>
   <input type="name" 
          name="name" _// this is important to be able to get our data //_
   />
   <button type="submit">Submit</button>
</form>
로그인 후 복사

이 접근 방식을 사용하면 event.target.value를 통해 데이터를 변경하기 위해 useState를 적용할 필요가 없습니다. 대신 myFunction에서 다음을 수행할 수 있습니다. 인수를 통해 변형된 데이터를 가져옵니다.

이는 양식의 요소에서 이름 속성을 설정해야 함을 의미합니다. 이 방법을 사용한다는 것은 이벤트 핸들러를 통해 수동으로 상태를 변경하는 대신 네이티브 React 양식 객체를 통해 React 양식 자체를 처리할 수 있다는 의미입니다.

서버 구성 요소: React 19를 사용하면 클라이언트 애플리케이션 또는 SSR 서버 설정과 별도의 환경에서 구성 요소를 번들링하기 전에 서버에서 렌더링할 수 있습니다. Server 구성 요소는 SSR(서버 측 렌더링)과 동일하지 않지만 React Server 구성 요소에는 별도의 서버 환경이 있습니다.
이 기능을 사용하면 구성 요소가 시간 전에 미리 렌더링될 수 있으므로 콘텐츠 표시가 빨라지고 로드 시간이 향상됩니다.

메타데이터: React 19는 유연한 메타데이터를 허용합니다. 개발자는 DocumentHead 컴포넌트를 통해 개별 컴포넌트의 제목, 설명 및 기타 메타 태그를 관리할 수 있습니다. 이는 SEO(검색 엔진 최적화)를 개선하는 데 도움이 됩니다.

Const AboutUs = () => {
 return (
    <>
      <title>Learn more about our company</title>
      <meta name="AboutUs" description="You can find us on ..." />
      // content
    </>
  );
}
로그인 후 복사

React 19에는 일련의 새로운 후크가 있습니다. 일부는 새로운 후크이며 일부는 기존 후크를 개선한 것입니다. 아래에서 이에 대해 논의해 보겠습니다.

use() 후크: use 후크는 구성 요소 또는 후크 내의 Promise 또는 컨텍스트 값을 읽는 데 직접 사용할 수 있는 실험적 API입니다(현재 알려진 유일한 제한 사항입니다). ).
use 후크는 매우 다양하며 비동기 데이터 가져오기에 사용할 수 있으므로 useEffect 대신 사용할 수도 있습니다. 이는
에 도움이 됩니다. 더 깔끔하고 간결한 코드 블록을 달성하세요.

주의사항: useEffect는 여전히 _useEffect가 제한 없이 실행된다는 자체 제한이 있기 때문에 이를 대체할 수 없습니다.

import {use} from "react"
const fetchData = async () => {
    const response = await fetch("https://........");
    return response.json()
}

const userData = () => {
    const user = use(fetchData());

        return (
    <div className='username'>{user.name}</div>
  );
}
로그인 후 복사

useActionState(): 상태 변경을 관리하는 데 도움이 되는 새로운 후크입니다. 보류 상태, 오류 처리, 최종 관리에 도움이 됩니다
상태 업데이트. useActionState는 2개의 매개변수(양식이 제출될 때 호출되는 함수 및 _initialState)를 수신하는 _useReduce_in과 유사하게 작동하며 3개의 값을 포함하는 배열을 반환합니다. 상태의 변형이 있는 경우 현재 상태가 되는 상태, 서버 작업을 호출하기 위해 양식 구성 요소에서 prop으로 전달될 수 있는 새로운 작업(formAction), 그리고 _isPending _은 _부울 _값을 반환하는지 여부 양식이 제출되었습니다.

import { useActionState } from "react";

async function incrementFunction(initialState, formData) {
  return initialState + 1;
}

function StatefulForm({}) {
  const [state, formAction, isPending] = useActionState(incrementFunction, 0);

  console.log(state);

  return (
    <form>
      <button formAction={formAction}>{state}</button>
    </form>
  )
}
로그인 후 복사

From this example, the incrementFunction adds 1 to the state every time the button is clicked. The initialState being 0, and then increases to 1 at the first click of the button, thereby changing the state to 1, and for every other click on the button adds 1 to the last state of the component.

useOptimistic() hook:

This is a new hook that allows users to see the outcome of their action even before the pages load completely. The pages are optimistically rendered to the user even when the server is still in its data fetching mode.

With the hope that data fetching will be successful, React displays the intended result to the client, and when data fetching fails, React reverts to the value of the previous state in order not to display incorrect data. This singular action helps in a seamless and fast display of data thereby improving user experience.

useFormStatus():

As the name implies, useFormStatus gives us the status of our form or form fields. This hook does not take in any parameter, but it sure returns 4 objects:

pending: This returns a boolean value: true or false. It returns true when the form is submitting, and false when the form is submitted.

data: When the form is successfully submitted, we can get the information of the user or object from the form field like this:

(formData.get("name"))
(formData.get("address"))
로그인 후 복사

method: The default method of a form is GET, unless stated otherwise. We can get the method of our form with .method. When we are submitting a form, a string method property should be specified as a POST.

action: This is a reference to the function that will be passed to the action prop in our element.

The useFormStatus must always be called from a element or a component that is rendered inside a .

There's quite a few more updates that I can't really write about, so you don't get bored having to read so much. You can click on the React Docs Website to check out some of the other updates.

I hope you had a great time learning with me.

Do well to follow me if you enjoyed my articles.

Thanks, and have a great week ahead my friends.

위 내용은 새로운 업데이트에 반응하세요의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!