【问题标题】:React TypeScript: Call function on route change using react-router-domReact TypeScript:使用 react-router-dom 在路由更改时调用函数
【发布时间】:2020-01-22 17:53:39
【问题描述】:

我希望 useEffect 能够控制日志,但项目无法编译并在终端出现错误 Unexpected use of 'location' no-restricted-globals 我不必使用 useEffect 如果我能在每次位置更改时触发一个函数会很高兴

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 };

【问题讨论】:

标签: reactjs typescript react-router-v4


【解决方案1】:

错误是自我描述的。您没有在任何地方声明变量名称location。如果是全局变量,你need to declare就这样:

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

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 2022-07-09
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2018-12-27
    • 2022-06-15
    相关资源
    最近更新 更多