【问题标题】:History not accessible from react-router-modalreact-router-modal 无法访问历史记录
【发布时间】:2019-08-03 02:19:47
【问题描述】:

您好,我在为最后使用的组件设置“react-router-modal”父路径时遇到问题

ModalRoute 和 ModalContainer 是 react-router-modal

App.js

class App extends Component {
  render() {
    return (
      <main>
        <Navbar />
        <BrowserRouter>
          <div>
            <Switch>
              <Route path="/main" component={ContentDefault} />
              <Route path="/search" component={SearchScreen} />
              <ModalRoute
                path="/register"
                parentPath="/"
                component={RegisterScreen}
              />
              <Route path="/contact" component={ContentDefault} />
              <Route component={ContentDefault} />
            </Switch>
            <ModalContainer />
          </div>
        </BrowserRouter>
        <Footer />
      </main>
    );
  }
}

export default App;

SearchScreen.jsx

import React, { Component } from "react";
import { withRouter } from "react-router-dom";

class SearchScreen extends Component {
  render() {
    return (
      <main>
        <h1>SearchScreen</h1>
      </main>
    );
  }
}

export default withRouter(SearchScreen);

例如,我在 mainScreen 上,然后我移动到 SearchScreen,然后我从导航栏打开模式。我需要我的模态返回到 SearchScreen

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom reactstrap


    【解决方案1】:

    我找到了一些可能对您有所帮助的解决方案。

    你可以试试这个:

    1. 创建状态prevPath

    2. 添加组件WillReceiveProps

    3. 如果 prevPath 为空,则向 parentPath 提供 prevPath 状态并将我重定向到路由'/'

      class App extends Component {
        state = { 
          prevPath: ''
         }
      
       componentWillReceiveProps(nextProps) {
         if (nextProps.location !== this.props.location) {
           this.setState({ prevPath: this.props.location })
         }
        }
      
       <ModalRoute
         path="/register"
         parentPath={this.state.prevPath || '/'}
         component={RegisterScreen}
        />
      

    如果没有帮助,我们可以稍后再尝试另一种解决方案。

    【讨论】:

    • 是的,但我需要它在模态中,从我打开模态为“parentPath”的女巫那里获取组件路径
    • 好的,这个 ModalRoute 是您创建的组件还是您从另一个库调用该组件?
    • 抱歉信息不足,这是 react-router-modal npmjs.com/package/react-router-modal的一部分
    • 我用可能很好的解决方案更新了我的答案,我不确定。
    猜你喜欢
    • 2019-05-09
    • 2018-11-07
    • 2023-03-30
    • 2020-02-25
    • 2016-01-07
    • 2017-08-03
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多