React 상태 관리의 진화: 로컬에서 비동기로
목차
- 소개
-
지역 주
- 클래스 구성요소
- 기능성 구성 요소
- useReducer 후크
-
글로벌 상태
- 글로벌 상태란 무엇입니까?
- 어떻게 사용하나요?
- 주요 길
- 간단한 방법
- 잘못된 길
- 비동기 상태
- 결론
소개
안녕하세요!
이 글은 수천 년 전 클래스 컴포넌트가 세상을 지배했고 기능적 컴포넌트가 단지 대담한 아이디어였을 때 최근까지 React 애플리케이션에서 상태가 어떻게 관리되었는지에 대한 개요를 제공합니다. , 상태의 새로운 패러다임이 등장했을 때: 비동기 상태.
지역 주
그렇습니다. 이미 React를 사용해 본 사람이라면 누구나 로컬 상태가 무엇인지 알고 있습니다.
상태가 업데이트될 때마다 구성요소가 다시 렌더링됩니다.뭔지 모르겠어요
로컬 상태는 단일 구성 요소의 상태입니다.
당신은 이 고대 구조물을 사용해 본 적이 있을 것입니다:
class CommitList extends React.Component { constructor(props) { super(props); this.state = { isLoading: false, commits: [], error: null }; } componentDidMount() { this.fetchCommits(); } fetchCommits = async () => { this.setState({ isLoading: true }); try { const response = await fetch('https://api.github.com/repos/facebook/react/commits'); const data = await response.json(); this.setState({ commits: data, isLoading: false }); } catch (error) { this.setState({ error: error.message, isLoading: false }); } }; render() { const { isLoading, commits, error } = this.state; if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; return ( <div> <h2>Commit List</h2> <ul> {commits.map(commit => ( <li key={commit.sha}>{commit.commit.message}</li> ))} </ul> <TotalCommitsCount count={commits.length} /> </div> ); } } class TotalCommitsCount extends Component { render() { return <div>Total commits: {this.props.count}</div>; } } }
아마도 현대적인 기능적인 것:
const CommitList = () => { const [isLoading, setIsLoading] = useState(false); const [commits, setCommits] = useState([]); const [error, setError] = useState(null); // To update state you can use setIsLoading, setCommits or setUsername. // As each function will overwrite only the state bound to it. // NOTE: It will still cause a full-component re-render useEffect(() => { const fetchCommits = async () => { setIsLoading(true); try { const response = await fetch('https://api.github.com/repos/facebook/react/commits'); const data = await response.json(); setCommits(data); setIsLoading(false); } catch (error) { setError(error.message); setIsLoading(false); } }; fetchCommits(); }, []); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; return ( <div> <h2>Commit List</h2> <ul> {commits.map(commit => ( <li key={commit.sha}>{commit.commit.message}</li> ))} </ul> <TotalCommitsCount count={commits.length} /> </div> ); }; const TotalCommitsCount = ({ count }) => { return <div>Total commits: {count}</div>; };
아니면 "더 많이 허용되는" 제품인가요? (확실히 더 드물지만)
const initialState = { isLoading: false, commits: [], userName: '' }; const reducer = (state, action) => { switch (action.type) { case 'SET_LOADING': return { ...state, isLoading: action.payload }; case 'SET_COMMITS': return { ...state, commits: action.payload }; case 'SET_USERNAME': return { ...state, userName: action.payload }; default: return state; } }; const CommitList = () => { const [state, dispatch] = useReducer(reducer, initialState); const { isLoading, commits, userName } = state; // To update state, use dispatch. For example: // dispatch({ type: 'SET_LOADING', payload: true }); // dispatch({ type: 'SET_COMMITS', payload: [...] }); // dispatch({ type: 'SET_USERNAME', payload: 'newUsername' }); };
궁금하게 만드는 것은...
왜 해킹 단일 구성 요소에 대해 이 복잡한 리듀서를 작성해야 합니까?
글쎄, React는 Redux라는 매우 중요한 도구로부터 useReducer라는 못생긴 후크를 물려받았습니다.
React에서 전역 상태 관리를 다루셨다면 Redux에 대해 들어보셨을 것입니다.
다음 주제인 글로벌 상태 관리로 이동합니다.
글로벌 상태
글로벌 상태 관리는 React를 배울 때 가장 먼저 복잡한 과목 중 하나입니다.
그것은 무엇입니까?
다양한 라이브러리를 사용하여 다양한 방식으로 구축된 여러 항목이 될 수 있습니다.
저는 이것을 다음과 같이 정의하고 싶습니다.
애플리케이션의 모든 구성 요소에서 액세스하고 유지 관리하는 단일 JSON 개체입니다.
const globalState = { isUnique: true, isAccessible: true, isModifiable: true, isFEOnly: true }
저는 다음과 같이 생각하고 싶습니다.
프런트 엔드 No-SQL 데이터베이스.
맞습니다. 데이터베이스입니다. 애플리케이션 데이터를 저장하는 곳으로 구성 요소가 읽기/쓰기/업데이트/삭제할 수 있습니다.
기본적으로 사용자가 페이지를 다시 로드할 때마다 상태가 다시 생성된다는 것을 알고 있지만 이는 원하는 대로 되지 않을 수 있으며, 데이터를 어딘가(예: localStorage)에 유지하는 경우 다음을 원할 수도 있습니다. 새로 배포할 때마다 앱이 손상되지 않도록 마이그레이션에 대해 알아보세요.
다음과 같이 사용하고 싶습니다.
구성요소가 자신의 감정을 전달하고 속성을 선택할 수 있는 다차원 포털입니다. 모든 것이 어디서나, 한 번에.
그것을 사용하는 방법?
주요 방법
리덕스
업계 표준입니다.
저는 7년 동안 React, TypeScript, Redux를 사용해 왔습니다. 제가 전문적으로 작업한 모든 프로젝트는 Redux를 사용합니다.
내가 만난 React로 작업하는 대다수의 사람들은 Redux를 사용합니다.
Trampar de Casa의 React 오픈 포지션에서 가장 많이 언급된 도구는 Redux입니다.
가장 인기 있는 React 상태 관리 도구는...
리덕스
React로 작업하려면 Redux를 배워야 합니다.
현재 React로 작업하고 계시다면 아마 이미 알고 계실 겁니다.
좋아요, Redux를 사용하여 일반적으로 데이터를 가져오는 방법은 다음과 같습니다.
이런 생각이 드셨다면 꼭 말씀드리고 싶습니다. 실제로 저는 Redux로 데이터를 가져오는 것이 아닙니다. 면책조항
"뭐라고요? 이게 말이 됩니까? Redux는 데이터를 가져오는 것이 아니라 데이터를 저장하는 것입니다. F가 Redux로 데이터를 어떻게 가져오나요?"
Redux는 애플리케이션의 캐비닛이 될 것이며 가져오기와 직접적으로 관련된 ~shoes~ 상태를 저장할 것입니다. 이것이 바로 제가 "Redux를 사용하여 데이터 가져오기"라는 잘못된 문구를 사용한 이유입니다.
// actions export const SET_LOADING = 'SET_LOADING'; export const setLoading = (isLoading) => ({ type: SET_LOADING, payload: isLoading, }); export const SET_ERROR = 'SET_ERROR'; export const setError = (isError) => ({ type: SET_ERROR, payload: isError, }); export const SET_COMMITS = 'SET_COMMITS'; export const setCommits = (commits) => ({ type: SET_COMMITS, payload: commits, }); // To be able to use ASYNC action, it's required to use redux-thunk as a middleware export const fetchCommits = () => async (dispatch) => { dispatch(setLoading(true)); try { const response = await fetch('https://api.github.com/repos/facebook/react/commits'); const data = await response.json(); dispatch(setCommits(data)); dispatch(setError(false)); } catch (error) { dispatch(setError(true)); } finally { dispatch(setLoading(false)); } }; // the state shared between 2-to-many components const initialState = { isLoading: false, isError: false, commits: [], }; // reducer export const rootReducer = (state = initialState, action) => { // This could also be actions[action.type]. switch (action.type) { case SET_LOADING: return { ...state, isLoading: action.payload }; case SET_ERROR: return { ...state, isError: action.payload }; case SET_COMMITS: return { ...state, commits: action.payload }; default: return state; } };
이제 UI 측면에서는 useDispatch 및 useSelector를 사용하여 작업과 통합합니다.
// Commits.tsx import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchCommits } from './action'; export const Commits = () => { const dispatch = useDispatch(); const { isLoading, isError, commits } = useSelector(state => state); useEffect(() => { dispatch(fetchCommits()); }, [dispatch]); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error while trying to fetch commits.</div>; return ( <ul> {commits.map(commit => ( <li key={commit.sha}>{commit.commit.message}</li> ))} </ul> ); };
Commits.tsx가 커밋 목록에 액세스하는 데 필요한 유일한 구성 요소인 경우 이 데이터를 전역 상태에 저장하면 안 됩니다. 대신 로컬 상태를 사용할 수 있습니다.
But let's suppose you have other components that need to interact with this list, one of them may be as simple as this one:
// TotalCommitsCount.tsx import React from 'react'; import { useSelector } from 'react-redux'; export const TotalCommitsCount = () => { const commitCount = useSelector(state => state.commits.length); return <div>Total commits: {commitCount}</div>; }
Disclaimer
In theory, this piece of code would make more sense living inside Commits.tsx, but let's assume we want to display this component in multiple places of the app and it makes sense to put the commits list on the Global State and to have this TotalCommitsCount component.
With the index.js component being something like this:
import React from 'react'; import ReactDOM from 'react-dom'; import thunk from 'redux-thunk'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import { Commits } from "./Commits" import { TotalCommitsCount } from "./TotalCommitsCount" export const App = () => ( <main> <TotalCommitsCount /> <Commits /> </main> ) const store = createStore(rootReducer, applyMiddleware(thunk)); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
This works, but man, that looks overly complicated for something as simple as fetching data right?
Redux feels a little too bloated to me.
You're forced to create actions and reducers, often also need to create a string name for the action to be used inside the reducer, and depending on the folder structure of the project, each layer could be in a different file.
Which is not productive.
But wait, there is a simpler way.
The simple way
Zustand
At the time I'm writing this article, Zustand has 3,495,826 million weekly downloads, more than 45,000 stars on GitHub, and 2, that's right, TWO open Pull Requests.
ONE OF THEM IS ABOUT UPDATING IT'S DOC
If this is not a piece of Software Programming art, I don't know what it is.
Here's how to replicate the previous code using Zustand.
// store.js import create from 'zustand'; const useStore = create((set) => ({ isLoading: false, isError: false, commits: [], fetchCommits: async () => { set({ isLoading: true }); try { const response = await fetch('https://api.github.com/repos/facebook/react/commits'); const data = await response.json(); set({ commits: data, isError: false }); } catch (error) { set({ isError: true }); } finally { set({ isLoading: false }); } }, }));
This was our Store, now the UI.
// Commits.tsx import React, { useEffect } from 'react'; import useStore from './store'; export const Commits = () => { const { isLoading, isError, commits, fetchCommits } = useStore(); useEffect(() => { fetchCommits(); }, [fetchCommits]); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error occurred</div>; return ( <ul> {commits.map(commit => ( <li key={commit.sha}>{commit.commit.message}</li> ))} </ul> ); }
And last but not least.
// TotalCommitsCount.tsx import React from 'react'; import useStore from './store'; const TotalCommitsCount = () => { const totalCommits = useStore(state => state.commits.length); return ( <div> <h2>Total Commits:</h2> <p>{totalCommits}</p> </div> ); };
There are no actions and reducers, there is a Store.
And it's advisable to have slices of Store, so everything is near to the feature related to the data.
It works perfect with a folder-by-feature folder structure.
The wrong way
I need to confess something, both of my previous examples are wrong.
And let me do a quick disclaimer: They're not wrong, they're outdated, and therefore, wrong.
This wasn't always wrong though. That's how we used to develop data fetching in React applications a while ago, and you may still find code similar to this one out there in the world.
But there is another way.
An easier one, and more aligned with an essential feature for web development: Caching. But I'll get back to this subject later.
Currently, to fetch data in a single component, the following flow is required:
What happens if I need to fetch data from 20 endpoints inside 20 components?
- 20x isLoading + 20x isError + 20x actions to mutate this properties.
What will they look like?
With 20 endpoints, this will become a very repetitive process and will cause a good amount of duplicated code.
What if you need to implement a caching feature to prevent recalling the same endpoint in a short period? (or any other condition)
Well, that will translate into a lot of work for basic features (like caching) and well-written components that are prepared for loading/error states.
This is why Async State was born.
Async State
Before talking about Async State I want to mention something. We know how to use Local and Global state but at this time I didn't mention what should be stored and why.
The Global State example has a flaw and an important one.
The TotalCommitsCount component will always display the Commits Count, even if it's loading or has an error.
If the request failed, there's no way to know that the Total Commits Count is 0, so presenting this value is presenting a lie.
In fact, until the request finishes, there is no way to know for sure what's the Total Commits Count value.
This is because the Total Commits Count is not a value we have inside the application. It's external information, async stuff, you know.
We shouldn't be telling lies if we don't know the truth.
That's why we must identify Async State in our application and create components prepared for it.
We can do this with React-Query, SWR, Redux Toolkit Query and many others.
이 글에서는 React-Query를 사용하겠습니다.
어떤 문제가 해결되는지 더 잘 이해하려면 각 도구의 문서에 액세스하는 것이 좋습니다.
코드는 다음과 같습니다.
데이터를 가져오기 위한 더 이상 작업, 파견, 전역 상태
가 없습니다.React-Query를 올바르게 구성하기 위해 App.tsx 파일에서 수행해야 하는 작업은 다음과 같습니다.
비동기 상태
는 특별합니다.슈뢰딩거의 고양이와 같습니다. 관찰(또는 실행)하기 전까지는 상태를 알 수 없습니다.
하지만 두 구성 요소 모두 useCommits를 호출하고 useCommits가 API 엔드포인트를 호출하는 경우 이는 동일한 데이터를 로드하기 위해 두 개의 동일한 요청이 있다는 뜻인가요?
짧은 답변: 아니요!
긴 답변: React Query는 정말 훌륭합니다. 이 상황을 자동으로 처리하며, 언제 데이터를 다시 가져오거나
캐시를 사용해야 하는지알 수 있을 만큼 스마트하게 사전 구성된 캐싱이 함께 제공됩니다.
또한 매우 구성 가능하므로 애플리케이션 요구 사항에 100% 맞게 조정할 수 있습니다.
이제 구성 요소는 항상 isLoading 또는 isError에 대비할 수 있으며 전역 상태를 덜 오염되게 유지하고 기본적으로 매우 깔끔한 기능을 갖췄습니다.
결론 이제 로컬, 글로벌,
비동기 상태의 차이점을 아셨습니다.
로컬 -> 구성요소만.
비동기 -> 슈뢰딩거의 고양이와 같은 외부 데이터는 로딩이 필요하고 오류를 반환할 수 있는 FE 애플리케이션 외부에 있습니다.
이 기사가 즐거웠기를 바랍니다. 다른 의견이나 건설적인 피드백이 있으면 알려주시기 바랍니다.위 내용은 React 상태 관리의 진화: 로컬에서 비동기로의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

프론트 엔드에서 VSCODE와 같은 패널 드래그 앤 드롭 조정 기능의 구현을 탐색하십시오. 프론트 엔드 개발에서 VSCODE와 같은 구현 방법 ...
