【问题标题】:React - Detect previous location at top level App component?React - 检测顶级应用程序组件的先前位置?
【发布时间】:2020-08-12 19:09:39
【问题描述】:

我需要检查我的应用中的位置变化,以便在用户离开某个页面后显示组件。 <Router> 内部的组件可以访问位置变量,但如何在顶层访问位置变量,<Router> 之外?这是我想要完成的一些伪代码 -

export const App = () => {
  const [showComponent, setShowComponent] = useState(false)  

  useEffect(() => {
    if (/* previous location === x */) {
      setShowComponent(true)
    }
  })

  return (
    <div>
      <Router>
        <Switch>
          ...
        </Switch>
      </Router>
      {showComponent && <Component />}
    </div>
  )
} 

【问题讨论】:

    标签: reactjs react-router react-hooks react-router-dom


    【解决方案1】:

    您不能真正在路由器之外访问它们(至少不能通过库...)。只需将依赖项向上移动即可。这是example

    index.js

    import React from "react";
    import ReactDOM from "react-dom";
    import { BrowserRouter as Router } from "react-router-dom";
    
    import App from "./App";
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <React.StrictMode>
        <Router>
          <App />
        </Router>
      </React.StrictMode>,
      rootElement
    );
    

    App.js

    import { withRouter, Switch } from "react-router-dom";
    import React from "react";
    import "./styles.css";
    
    function App({ history, location }) {
      console.log(history, location);
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          <Switch>{/* Add routes here */}</Switch>
        </div>
      );
    }
    
    export default withRouter(App);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-28
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多