일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- count
- state
- leetcode
- DP
- Context
- priority_queue
- JSX
- BinaryTree
- 비트연산
- treenode
- c++
- Callback
- MySQL
- component
- event
- array
- Navigation
- bit
- React
- nodeJS
- routes
- UE5
- queue
- map
- node.js
- Props
- css
- route
- axios
- server
- Today
- Total
우사미 코딩
[React] Navigation 만들기 (1) - navigation.js 본문
페이지 url을 입력했는데 리엑트에서는 url에 따른 페이지 렌더링을 어떻게 해야하지?
할때 navigation을 사용하면 됨
여기에서는 window.history.pushState로 페이지를 이동하는것처럼 보이게 할거임
이렇게 했을 때 장점이 뭐냐면 페이지가 refresh 되지 않는 것이다
그럼 main->signup페이지로 이동한다고 했을 때 main에서 선언했던 변수들이 signup페이지에서도 사용이 가능한 것임
이를 위해 navigation을 만들 것이당
네비게이션을 지원하는 라이브러리도 많다고 하지만
강사쓰앵님이 알려주신대로 한번 해봄
window.history.pushState({}, '', '/accordion')
한다음 이벤트 추가하면 기존에 어느 페이지에 있었는지 보여짐
window.addEventListener('popstate', ()=>console.log('im at', window.location.pathname));
- 파일경로 : src/context/navigation.js
import { createContext, useState, useEffect } from "react";
const NavigationContext = createContext();
function NavigationProvider({children}) {
const [currentPath, setCurrentPath] = useState(window.location.pathname);
// console.log(currentPath);
useEffect(()=>{ // document.ready
const handler= ()=>{
setCurrentPath(window.location.pathname);
};
window.addEventListener('popstate', handler);
// popstate 이벤트는 브라우저의 히스토리 항목 변경을 감지 (예: 사용자가 뒤로가기 버튼을 클릭할 때)
return () => {
//NavigationProvider가 screen에서 remove될 때 removeEventhandler
window.removeEventListener('popstate', handler);
};
}, []);
const navigate = (to) => { // to: /accordion
window.history.pushState({}, '', to);
setCurrentPath(to);
};
return <NavigationContext.Provider value={{}}>
<div>
<button onClick={()=>navigate('/main')}>** Go to main **</button>
<button onClick={()=>navigate('/signup')}>** Go to Signup **</button>
</div>
{currentPath}
{children}
</NavigationContext.Provider>
};
export {NavigationProvider};
export default NavigationContext;
- index.js
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { NavigationProvider } from './context/navigation';
const el = document.getElementById('root');
const root = ReactDOM.createRoot(el);
root.render(
<NavigationProvider>
<App />
</NavigationProvider>
);
App을 NavigationProvider로 감싼다
그럼 아래와 같이 pathname이 달라지면 현재 표시되는 것{currentPath}도 달라짐
뒤로가기 버튼 눌러도 페이지 새로고침이 없으면서 currentPath가 업데이트된다
그럼 최종적으로 provider의 value에 currentPath와 navigate함수를 넣으면 끝난다
//// before
const navigate = (to) => { // to: /accordion
window.history.pushState({}, '', to);
setCurrentPath(to);
};
return <NavigationContext.Provider value={}>
<div>
<button onClick={()=>navigate('/main')}>** Go to main **</button>
<button onClick={()=>navigate('/signup')}>** Go to Signup **</button>
</div>
{currentPath}
{children}
</NavigationContext.Provider>
//// after
const navigate = (to) => { // to: /accordion
window.history.pushState({}, '', to);
setCurrentPath(to);
};
return <NavigationContext.Provider value={{ currentPath, navigate}}>
{children}
</NavigationContext.Provider>
navigation.js 코드에 대한 설명
이 코드는 React Context API를 사용해 웹사이트의 현재 경로를 상태로 관리하는 것입니다. 이를 통해 애플리케이션의 어느 부분에서든 현재 경로에 대한 정보를 쉽게 가져올 수 있습니다. 이는 라우팅, 네비게이션 업데이트 등의 상황에서 유용할 수 있습니다.
상세한 기능은 다음과 같습니다.
- `NavigationContext`를 생성합니다. 이는 React의 Context API를 사용하여 애플리케이션 전체에서 사용할 수 있는 `currentPath`라는 상태를 만듭니다. 이 값은 웹사이트의 현재 경로를 나타냅니다.
- `NavigationProvider`라는 컴포넌트를 선언합니다. 이 컴포넌트는 초기에 `currentPath` 상태를 현재 window의 location.pathname으로 설정합니다.
- `NavigationProvider` 컴포넌트가 마운트되면, `useEffect`를 사용하여 'popstate' 이벤트 리스너를 추가합니다. `popstate` 이벤트는 브라우저의 히스토리 항목 변경을 감지합니다 (예: 사용자가 뒤로가기 버튼을 클릭할 때). 이 때, `setCurrentPath` 함수가 호출되어 `currentPath` 상태를 업데이트합니다.
- 컴포넌트가 언마운트될 때 (화면에서 사라질 때), `useEffect`의 클린업 함수를 통해 'popstate' 이벤트 리스너를 제거합니다. 이렇게 함으로써 필요 없는 메모리 사용을 방지하고 성능을 개선합니다.
- `NavigationProvider`는 자식 컴포넌트에게 `currentPath` 상태를 제공합니다. 이를 통해 다른 컴포넌트에서 현재 경로 정보를 쉽게 사용할 수 있습니다.
- 그리고 `currentPath`를 출력하여 현재 경로를 화면에 보여줍니다.
마지막으로, `NavigationProvider`와 `NavigationContext`를 내보내어 다른 파일에서 사용할 수 있게 합니다.
mount, unmount에 대해
"마운트(mount)"와 "언마운트(unmount)"는 리액트(React)에서 많이 사용되는 개념들입니다. 컴포넌트의 생명주기에 따라 발생하는 이벤트를 나타냅니다.
- **마운트(mount)**: 마운트란 React에서 컴포넌트가 처음으로 DOM에 삽입되는 것을 의미합니다. 즉, 컴포넌트가 브라우저 화면에 처음으로 그려질 때를 말합니다. `componentDidMount` 라는 생명주기 메서드가 있으며, 이 메서드는 컴포넌트가 처음으로 마운트될 때 한 번만 호출됩니다. 함수형 컴포넌트에서는 `useEffect` 훅의 종속성 배열을 빈 배열로 두어 마운트시 동작을 표현할 수 있습니다.
- **언마운트(unmount)**: 반대로 언마운트란 컴포넌트가 DOM에서 제거되는 것을 의미합니다. 즉, 컴포넌트가 더 이상 화면에 나타나지 않을 때를 말합니다. `componentWillUnmount` 라는 생명주기 메서드가 있으며, 이 메서드는 컴포넌트가 언마운트되기 직전에 한 번만 호출됩니다. 함수형 컴포넌트에서는 `useEffect` 훅에서 클린업 함수를 반환함으로써 언마운트시 동작을 표현할 수 있습니다.
위의 설명에서 사용한 생명주기 메서드들은 클래스 컴포넌트에 사용되며, 함수형 컴포넌트에서는 `useEffect` 훅을 사용하여 비슷한 기능을 수행할 수 있습니다. `useEffect`의 클린업 함수는 컴포넌트가 언마운트되거나, 새로운 렌더링 사이클이 시작될 때 호출됩니다.
'React' 카테고리의 다른 글
[React] Navigation 만들기 (4) - 스타일링 보강하기 (0) | 2023.07.22 |
---|---|
[React] Navigation 만들기 (3) - Link 기능 보강하기 (새탭에서 열기) (0) | 2023.07.22 |
[React] 느린 데이터 환경에서 테스트하기 (0) | 2023.07.06 |
[React] redux - useSelector로 여러 value 반환하기 (0) | 2023.07.05 |
[React] extraReducer (0) | 2023.07.05 |