【问题标题】:React router open modalReact 路由器打开模式
【发布时间】:2018-08-13 11:33:19
【问题描述】:

我是 react 和 redux 世界的新手。我有一个关于反应路由器的问题。以下是我的 App 组件。

class App extends React.PureComponent {
  render() {
    return (
      <div>
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/callback" component={CallbackPage} />
          <Route exact path="/list" component={List} />
          <Route component={NotFoundPage} />
        </Switch>
      </div>
    );
  }
}
export default App;

我的列表类如下所示:

export class List extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
    };

    this.depositHandleToggle = this.depositHandleToggle.bind(this);
  }
  depositHandleToggle = () => {
    this.props.dispatch(push(`${this.props.match.url}/deposit`));
  }
  render() {
    const { match } = this.props;
    return (
      <div>
      <Route path={`${match.url}/deposit`} component={Modal} />
        <button onClick={this.depositHandleToggle}>Open Modal</button>  
      </div>
    );
  }
}
export default List;

所以我的问题是:当我单击列表容器中的按钮时,为什么我的路由器找不到这个 url 'localhost:xxx/list/deposit'?它呈现 App 组件,但它永远不会返回到 List 组件。是否可以在我的列表容器中包含自定义路由?难道我做错了什么?请有人帮我解决这个问题。

希望你能理解我的问题。提前致谢。

回答:

我找到了答案,问题出在我的 App 组件列表路径中。我有 'exact' 关键字,这就是我的列表组件中的路由不起作用的原因。遵循的方式是正确的方式。

<Route path="/list" component={List} />

我希望这会对某人有所帮助。

【问题讨论】:

    标签: reactjs redux react-router react-redux redux-router


    【解决方案1】:
    import { Link } from 'react-router-dom';
    class App extends React.PureComponent {
      render() {
        return (
          <div>
            <Switch>
              <Route exact path="/" component={HomePage} />
              <Route exact path="/callback" component={CallbackPage} />
              <Route exact path="/list" component={List} />
              <Route exact path="/list/deposit" component={Modal} />
              <Route component={NotFoundPage} />
            </Switch>
          </div>
        );
      }
    }
    export default App;
    
    export class List extends React.PureComponent {
      constructor(props) {
        super(props);
      }
    
      render() {
        const { match } = this.props;
        return (
          <div>
          <Link to={'/deposit'}>Open Modal</Link> 
        );
      }
    }
    export default List;
    

    在该组件中,您应该处理模态打开关闭。

    【讨论】:

    • 你能给我一个例子吗?
    • 查看示例
    • 我去看看
    • 仍然是 'localhost:xxx/list',但我希望它是 'localhost:xxx/list/deposit'。并且不会触发 Modal 组件的渲染方法?
    • 我的意思是你应该在应用组件中定义它,在其他组件和路由中添加。
    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多