javascript - react 路由器 v4 : Determine if route has been matched from outside the component

标签 javascript reactjs react-router-v4

我有一个总是需要渲染的组件,但只有在没有匹配的路由时才应该可见(<Iframe isVisible={ifNoRoutesMatched} />)。

到目前为止,我还没有找到一个很好的方法来检查是否是这种情况。我走下了这条可怕的路线,将变量设置为组件包装器状态,但必须有更好的方法!?这也需要 withRouterPureComponent否则 catchAllWrapper导致无限渲染循环:

class App extends PureComponent {
  state = {
    routeMatched: false,
  }

  catchAllWrapper = () => {
    this.setState({ routeMatched: false });
    return null;
  }

  routeWrapper = (RouteComponent) => {
    const RouteWrapper = (props) => {
      this.setState({ routeMatched: true });
      return <RouteComponent {...props} />;
    };

    return RouteWrapper;
  }

  render() {
    return (
      <div className="App">
        <Navigation />
        <Switch>
          <Route path="/chat" component={this.routeWrapper(Chat)} />
          ...more routes...
          <Route component={this.catchAllWrapper} />
        </Switch>
        <Iframe isVisible={!this.state.routeMatched} />
      </div>
    );
  }
}

export default withRouter(App);

我宁愿手动比较路由字符串数组也不愿增加这种复杂性!

this.props.match只有在匹配组件内部匹配的路由信息​​,所以它非常无用。

有更好的方法吗?

用例:它是一个 iframe,在某些路由上加载了旧版应用程序,因此不应在路由之间销毁和重新呈现它

最佳答案

为什么不为路由器创建一个轻量级虚拟组件以自由挂载和卸载,然后将当前类的回调方法绑定(bind)到它的生命周期事件?

class Dummy extends Component {
  componentDidMount() {
    this.props.didMount();
  }

  componentWillUnmount() {
    this.props.willUnmount();
  }

  render() {
    return null;
  }
}

class App extends Component {
  state = {
    showIframe: false,
  }

  cbDidMount = () => {
    this.setState({ showIframe: true });
  }

  cbWillUnmount = () => {
    this.setState({ showIframe: false });
  }

  render() {
    return (
      <div className="App">
        <Navigation />
        <Switch>
          <Route path="/chat" component={Chat} />
          {/* more routes */}
          <Route render={() => <Dummy didMount={this.cbDidMount} willUnmount={this.cbWillUnmount} />} />
        </Switch>
        <Iframe isVisible={this.state.showIframe} />
      </div>
    );
  }
}

关于javascript - react 路由器 v4 : Determine if route has been matched from outside the component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53325062/

相关文章:

reactjs - 不同的布局 - React Router v4

javascript - React - 发出请求后如何重定向到另一个组件?

javascript - 将 Promise 转换为同步函数

javascript - 真的有必要使用react-bootstrap提供的组件吗?

javascript - 在 mousedown 元素之外捕获 mouseup 的最佳方法

javascript - 如何使用javascript隐藏滚动条而不影响主体宽度?

javascript - 未捕获错误 : A cross-origin error was thrown. React 无法访问开发中的实际错误对象

reactjs - 使用 React Router 处理 'Overlay Pages'?

javascript - 如何使用 pdf.js 从 pdf 文档获取元数据

javascript - 如何获取 iframe 的父元素(不仅仅是窗口)?