[react] react-router-domとhooks

import React, {useState, useEffect} from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';

const paramsList = [];
const locationList = [];
const historyList = [];
const CountUp = props => {
 const [state, setState] = useState(0);
 const {match, location, history} = props;
 const {params} = match;
 
 useEffect(() => {
   paramsList.push(params);
   locationList.push(location);
   historyList.push(history);
   
   if (paramsList.length >= 2) {
     const prevIndex = paramsList.length - 2;
     const currentIndex = paramsList.length - 1;
     // いずれも常に true になる
     console.log(Object.is(paramsList[prevIndex], paramsList[currentIndex]));
     console.log(
       Object.is(locationList[prevIndex], locationList[currentIndex])
     );
     console.log(Object.is(historyList[prevIndex], historyList[currentIndex]));
   }
 });
 
 return (
   <div>
     <p>{state}</p>
     <button
       type="button"
       onClick={() => {
         setState(s => s + 1);
       }}
     >
       click
     </button>
   </div>
 );
};

const App = () => (
 <BrowserRouter>
   <Switch>
     <Route path="/component/:pageId" component={CountUp} />
   </Switch>
 </BrowserRouter>
);

export default App;

今までは<Route />のプロパティのコンポーネントの引数から

const {match, location, history} = props;

こんな感じでhistoryなどを使用していた。

Hooksを使うと以下のようにかける

import React, {useState, useEffect} from 'react';
import {
  BrowserRouter,
  Switch,
  Route,
  useParams,
  useLocation,
  useHistory,
} from 'react-router-dom';

const paramsList = [];
const locationList = [];
const historyList = [];

const CountUp = () => {
  const [state, setState] = useState(0);
  const params = useParams();
  const location = useLocation();
  const history = useHistory();
  useEffect(() => {
    paramsList.push(params);
    ...

const App = () => (
  <BrowserRouter>
    <Switch>
      <Route path="/component/:pageId">
        <CountUp />
      </Route>
    </Switch>
  </BrowserRouter>
);

useHistory()などは<Route />に定義していないどのコンポーネントからでもアクセスできるようになっている?

この記事が気に入ったらサポートをしてみませんか?