React TypeScript:使用react-router-dom更改路线时调用函数

时间:2019-09-22 12:34:39

标签: reactjs typescript react-router-v4

我希望useEffect能够控制台日志,但是项目无法编译并在终端Unexpected use of 'location' no-restricted-globals中给出错误,如果每次位置更改时都可以触发函数,我不必使用useEffect将很高兴< / p>

import React, { useState, useEffect } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import { Context } from "./components/context";
import { Layout } from "./components/layout";
import { Home } from './routes/home';
import { NotFound } from './routes/not-found';

const Router: React.FC = () => {

  useEffect(() => {
    console.log('location changed')
  }, [location]);

  return (
    <Context.Provider value={{ global, setGlobal }}>
      <BrowserRouter>
        <Route render={({location}) => ( //<-------- this is the location!!!
          <Layout>
            <TransitionGroup>
              <CSSTransition timeout={450} classNames='fade' key={location.key}>
                <Switch location={location}>
                  <Route exact path = '/' component = {Home} />
                  <Route exact path = '/my/profile/' component = {Home} />
                  <Route component = {NotFound}/>
                </Switch>
              </CSSTransition>
            </TransitionGroup>
          </Layout>
        )} />
      </BrowserRouter>
    </Context.Provider>
  );
}

export { Router };

1 个答案:

答案 0 :(得分:0)

该错误是自描述的。您没有在任何地方声明变量名location。如果它是全局变量,则像这样need to declare

Filename: global.d.ts
declare var location: type