【问题标题】:React Router component inside modal won't update模态中的 React Router 组件不会更新
【发布时间】:2020-10-03 07:45:26
【问题描述】:

我正在尝试在 Material-UI 的模式内创建登录和注册页面,当用户单击使用 React Router Switch 时,它应该在这两个组件之间来回切换

但问题是每当我点击 . URL 已更改,但我的组件不会更新(它保持相同的旧组件)下面是我的代码。

import Modal from "@material-ui/core/Modal";
import { Switch, Link, Route, BrowserRouter as Router } from "react-router-dom";


export default function AccountModal() {
    .
    .
    .
    const SignIn = () => {
        return (
            <div className="modal__body">
                <p>Don't have an account? <Link to="/signup">Sign up</Link></p>
            </div>
        );};

    const SignUp = () => {
        return (
            <div className="modal__body">
                <p>Already have an account? <Link to="/">Log inp</Link></p>
            </div>
        );};

return (
    <>
        <Button onClick={() => setOpen(true)} className={classes.button}>Get started!</Button>
        <Modal open={open} onClose={() => setOpen(false)}>
            <Router>
                <div style={modalStyle} className={classes.paper}>
                    <div className="modal__header">
                        <center><img src={logo} alt="Logo"></img></center>
                    </div>

                    <Switch>
                        <Route path="/" component={SignIn} />
                        <Route path="signup" component={SignUp} />
                    </Switch>

                </div>
            </Router>
        </Modal>
    </>
);
}

对于任何令人困惑的英语语言和写作,我深表歉意,我目前正在学习如何使用 React。提前谢谢!

【问题讨论】:

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


    【解决方案1】:

    Switch 将渲染第一个匹配位置的RouteRedirect,“/”匹配所有路由。交换顺序,以便首先尝试匹配更具体的路径。

    <Switch>
      <Route path="/signup" component={SignUp} />
      <Route path="/" component={SignIn} />
    </Switch>
    

    或在登录路由上指定 exact 属性,因此路径必须与“/”完全匹配,不再赘述

    <Switch>
      <Route exact path="/" component={SignIn} />
      <Route path="/signup" component={SignUp} />
    </Switch>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多