본문 바로가기

React

react-router-dom (5) 부가기능 history

history

- 객체

- 라우트로 사용된 컴포넌트에 match, location과 함께 전달되는 props 중 하나

- 컴포넌트 내에 구현하는 메서드에서 라우터 API 호출할 때 사용

eg. 특정 버튼을 눌렀을 때 뒤로가기, 로그인 후 화면 전환, 다른 페이지로의 이탈 막기 등등

 

 

 

1. HistorySample.js

import React, { Component } from "react";

class HistorySample extends Component {
  handleGoBack = () => {
    this.props.history.goBack();
  };

  handleGoHome = () => {
    this.props.history.push("/");
  };

  componentDidMount() {
    //페이지에 변화가 생기려고 할 때마다 정말 나갈 것인지 질문
    this.unblock = this.props.history.block("you really want to leave me?");
  }

  componentWillUnmount() {
    //컴포넌트가 언마운트 되면 질문 멈추기
    if (this.unblock) {
      this.unblock();
    }
  }
  render() {
    return (
      <div>
        <button onClick={this.handleGoBack}>Go Back</button>
        <button onClick={this.handleGoHome}>Go Home</button>
      </div>
    );
  }
}

export default HistorySample;

 

 

 

 

 

2. App.js

 

import React from "react";
import { Route, Link } from "react-router-dom";
import Home from "./component/Home";
import About from "./component/About";
import Profiles from "./component/Profiles";
import HistorySample from "./component/HistroySample";

import "./App.css";

const App = () => {
  return (
    <div>
      <ul>
        <li>
          <Link to="/">HOME</Link>
        </li>
        <li>
          <Link to="/about">ABOUT</Link>
        </li>
        <li>
          <Link to="/profiles">PROFILE</Link>
        </li>
        <li>
          <Link to="/history">History Sample</Link>
        </li>
      </ul>
      <hr />
      <Route path="/" component={Home} exact={true} />
      <Route path={["/about", "/info"]} component={About} />
      <Route path="/profiles" component={Profiles} />
      <Route path="/history" component={HistorySample} />
    </div>
  );
};
export default App;

 

김민준, 리액트를 다루는 기술 개정판, 2019년, 324-344페이지