How can I check if react-router is in context?

ε祈祈猫儿з 提交于 2020-06-01 05:18:05

问题


I'm migrating an AngularJS app to React little by little, and I would like to have a custom RouterLink React component that checks if react-router is in context so it can use history, and if not, falls back to usage of good old window.location. But I don't see any way of checking that in react-router's documentation.

I tried using withRouter but it throws when not in context and an ErrorBoundary doesn't seem to catch the error.

Does anyone know how I could go about doing this?


回答1:


There is Router context exposed in react-router package, i.e. __RouterContext, by using that you can check if router is avaiable:

import React, { useContext } from 'react';
import { __RouterContext } from 'react-router';

const MyComponent = (props) => {
  const router = useContext(__RouterContext);

  if (router) {
    // Router context is avaible
  } else {
    // Use window.location as router context is not availble in this component
  }

  return <SomeOtherComponent />
}



回答2:


Just wrap the hook in a try/catch:

const {useState, useEffect, Fragment} = React;
const {useLocation, MemoryRouter} = ReactRouter;

const Cmp = () => {
  let loc;
  try {
    loc = useLocation();
  } catch (err) {
    return (
      <div>No Router Available</div>
    );
  }
  return (
    <div>Hello I can see {loc.pathname}</div>
  );
};

const App1 = () => {
  return (
    <Cmp/>
  );
};

const App2 = () => {
  return (
    <MemoryRouter>
      <Cmp/>
    </MemoryRouter>
  );
};

ReactDOM.render(<App1 />, document.getElementById("app1"));
ReactDOM.render(<App2 />, document.getElementById("app2"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-router@5.1.2/umd/react-router.js"></script>

<div id="app1"></div>
<div id="app2"></div>


来源:https://stackoverflow.com/questions/59992359/how-can-i-check-if-react-router-is-in-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!