(TIL 14일차) React (3)

빡기·2020년 2월 11일
0

TIL(Today I Learned)

목록 보기
6/43

코드카타 고찰

const reverse = x => {
  const list = x.toString().split("")
  if(list[0] === "-"){
    const minus = list.shift();
    return Number(minus+list.reverse().join(""))
  }
  return Number(list.reverse().join(""))
}
  • sort,reverse를 사용하려면 배열안에 삽입해야 함
  • join("")은 스트링으로 만들어주고 split("")은 스트링을 배열로 만들어 줌
  • parseInt는 "100px"를 100으로 Number는 무조건 100인것만 인식

Router

  • SPA(싱글 페이지 어플리케이션)의 중요한 요소
  • 기존 페이지 방식으로 수시로 서버로 부터 리소스를 받아 렌더링을 하면 자원의 비효율적인 면과 불필요한 트래픽 발생
  • react의 필수 써드 파티 라이브러리
  • Router는 기본적으로 match,location,history prop를 가짐
  • Router의 props를 컴포넌트에서 사용하려면 WithRouter로 export에 씌어줘야 함

단점

  • 앱의 규모가 커지면 js파일 사이즈 크기가 너무 커짐
  • 방문하지 않은 페이지에 대한 렌더핑 스크립트도 로드
  • 크롤러에서 페이지의 정보를 제대로 가져가지 못함
  • 검색엔진에 나타나지 않음
  • Code Splitting을 사용하면 해결
const App = () => {
  return (
    <div>
      <Switch> // switch 사용시 규칙이 일치하는 라우트 단 한개만 렌더
        	   // 아무것도 일치 하지 않으면 Not Found error
      <Route path="/" exact component={Home} /> 
      <Route path="/about" component={About} />
      </Switch>
    </div>
  );
};
  • Router의 기본적인 구조
  • 해당하는 path(url경로)로 접근하면 해당 컴포넌트 렌더
  • exact를 작성해줘야 url 겹치는 현상 방지 가능

const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to="/"></Link>
        </li>
        <li>
          <Link to="/about">소개</Link>
        </li>
      </ul>
      <hr />
    </div>
  );
};
  • 기존의 a태그와는 다르게 새로운 페이지에서 새로운 렌더링을 진행하지만 Link는 브라우저의 주소만 바꿀뿐이지 페이지를 새로 불러오지 않아서 효율적
 <NavLink
     to="/profiles/velopert"
     activeStyle={{ background: 'black', color: 'white' }}
 >
</NavLink>
  • Link와 비슷하지만 경로 일치하는 경우 특정스타일 혹은 스타일클래스 적용 가능한 컴포넌트
  • css적용말고 css클래스 적용시 activeClassName를 사용!

파라미터와 쿼리

/profiles/velopert // 파라미터
/about?details=true // 쿼리
  • 파라미터 : 특정 id나 이름 조회 params를 이용할 때는 match로❗❗
  • 쿼리 : 키워드 값 검색,요청,옵션 쿼리로 탐색할 때는 location으로❗❗
  • 유동적인 값을 전달할때 사용

URL Params 값 가져오기

- match를 이용한 방법

<Route path="/" exact={true} component={Home} />
<Route path="/about" component={About} />
<Route path="/profiles/:username" component={Profile} />
//:username이라는 값을 파라미터로 인식하여 값으로써 전달 가능

const Profile = ({ match }) => {
 
  // 파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조
  const { username } = match.params;
  return (
    <div>
        {username} // url 뒤에 지정해 놓은 변수 값 받아와 사용
    </div>
  );
};
  • match객체 안에는 현재의 주소 정보 존재
  • params -(객체) 경로의 동적 세그먼트에 해당하는 URL에서 구문 분석 된 키 / 값 쌍
  • path-(문자열) 일치하는 데 사용되는 경로 패턴, 중첩 된 Router 구축에 유용

URL Query 값 가져오기

  • location 및 match가 가지고 있는 정보


    - location 이용해서 search 값 가져오기

    {
     key: 'ac3df4',
     pathname: '/somewhere'
     search: '?some=search-string',
     hash: '#howdy',
     state: {
       [userDefined]: true
     }
    }
    const About = ({ location }) => {
     const query = qs.parse(location.search, {
       ignoreQueryPrefix: true
     });
     const detail = query.detail === 'true'; 
     // 쿼리의 파싱결과값은 문자열
    
  • qs말고 json.parse, json.stringify 사용 가능

- histroy 이용해서 뒤로가기,특정경로 이동, 이탈 방지

function HistorySample({ history }) {
  const goBack = () => {
    history.goBack();
  };
// 페이지 뒤로가기
  const goHome = () => {
    history.push('/');
  };
// 페이지 "/"로 이동
 useEffect(() => {
    console.log(history);
    const unblock = history.block('정말 떠나실건가요?');
    return () => {
      unblock();
    };
  }, [history]);
  // 이탈하려는 순간 위의 메소드 실행

서브 라우터

// app.js
const App = () => {
  return (
<div>
      <ul>
        <li>
          <Link to="/"></Link>
        </li>
        <li>
          <Link to="/about">소개</Link>
        </li>
        <li>
          <Link to="/profiles">프로필 목록</Link>
        </li>
      </ul>
      <hr />
      <Route path="/" exact={true} component={Home} />
      <Route path="/about" component={About} />
      <Route path="/profiles" component={Profiles} />
    </div>
    )
  
  // profiles.js
   <div>
      <h3>유저 목록:</h3>
      <ul>
        <li>
          <Link to="/profiles/velopert">velopert</Link>
        </li>
        <li>
          <Link to="/profiles/gildong">gildong</Link>
        </li>
      </ul>

      <Route
        path="/profiles"
        exact
        render={() => <div>유저를 선택해주세요.</div>}
      />
      <Route path="/profiles/:username" component={Profile} />
    </div>
  • 특정 라우트 내에 탭 같은 것을 만들게 되며 단순히 state 보다 서브 라우트로 관리하는 게 편함
  • setState가 불필요하고 링크를 통해 쉽게 진입

witchRouter Hoc

  • 라우트 컴포넌트가 아닌곳에서 match,location,history 사용해야할 때 적용
import React from 'react';
import { withRouter } from 'react-router-dom';
const WithRouterSample = ({ location, match, history }) => {
  return (
    <div>
      <h4>location</h4>
      <textarea value={JSON.stringify(location, null, 2)} readOnly />
      <h4>match</h4>
      <textarea value={JSON.stringify(match, null, 2)} readOnly />
      <button onClick={() => history.push('/')}>홈으로</button>
    </div>
  );
};
export default withRouter(WithRouterSample);
  • 사용시 자신의 부모 컴포넌트 기준의 match 값 전달

profile
Front End. Dev

0개의 댓글