【问题标题】:Disappearing of components while using react-router in React在 React 中使用 react-router 时组件消失
【发布时间】:2020-02-20 16:35:58
【问题描述】:

所以,我一直在构建一个 React 应用程序,并且我一直面临刷新时组件消失的类似问题,更准确地说,它与反应路由器有关,我一定是使用不正确

App.js 的样子

import React from "react";
import "./App.css";
import { Home } from "./components/home";

function App() {
 return <Home />;
}

export default App

主页组件

export class Home extends Component {
render() {
  return (
    <BrowserRouter>
      <NavigationBar />
      <Switch>
        <Route path="/jobPortal" component={JobPortal} />
      </Switch>
    </BrowserRouter>
  );
}

通用导航栏

const NavigationBar = ({ userType }) => {
  return (
    <Navbar style={globalStyles.container} bg="dark" variant="dark">
      <Navbar.Brand style={globalStyles.container} href="/">
        Soffice
      </Navbar.Brand>
      <Nav className="ml-auto">
        <Nav.Link as={NavLink} to="/JobPortal">
          Job Portal
        </Nav.Link>
        {userType && (
          <Nav.Link as={NavLink} to="/logout">
            Log Out
          </Nav.Link>
        )}

        {!userType && (
          <React.Fragment>
            <Nav.Link as={NavLink} to="/SignUp">
              Sign Up
            </Nav.Link>
            <Nav.Link as={NavLink} to="/SignIn">
              Sign In
            </Nav.Link>
          </React.Fragment>
        )}
      </Nav>
    </Navbar>
  );
};

导出默认导航栏;

访问jobPortal时出现的Job Navbar

const NavigationBar = ({ url }) => {
  // let {url,url} =useRouteMatch();
  console.log(url);
  return (
    <Navbar style={{ ...globalStyles.container }} bg="info" variant="dark">
      <Nav className="mx-auto">
        <Nav.Link style={styles.navBarColor} as={NavLink} to="/JobPortal">
          Home
        </Nav.Link>
        <Nav.Link style={styles.navBarColor} as={NavLink} to={`${url}/Post`}>
          Post Job
        </Nav.Link>
        <Nav.Link style={styles.navBarColor} as={NavLink} to={`${url}/Want`}>
          Want Job
        </Nav.Link>
        <Nav.Link style={styles.navBarColor} as={NavLink} to={`${url}/Contact`}>
          Contact
        </Nav.Link>
      </Nav>
    </Navbar>
  );
};
const styles = {
  navBarColor: {
    color: "white",
    fontSize: 22
  }
};
export default NavigationBar;

JobPortal 组件

export class JobPortal extends Component {
  componentDidMount() {
    console.log("path", this.props.match.url);
  }
  render() {
    const path = this.props.match.path;

    return (
      <BrowserRouter>
        <NavigationBar url={this.props.match.url} />
        <Switch>
          <Route path={`${path}/Want`} component={Want} />
        </Switch>
      </BrowserRouter>
    );
  }
}

想要的组件

class Want extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      email: "",
      message: "",
      jobs: [
        {
          jobId: 1,
          jobTitle: "software"
        }
      ]
    };
  }

  handleClick() {
    console.log(this.state);
  }
  componentWillMount() {
    this.url = this.props.location.pathname;
    console.log("location", this.props.location.pathname);
  }
  render() {
    const styles = {
      card: {
        width: "14em",
        height: "100%",
        fontSize: 20,
        padding: 10
      }
    };
    return (
      <BrowserRouter>
        <Route path={`${this.url}/:jobId`} component={Job} />
        <Container>
          <Container></Container>
          <Container>
            <Row>
              {this.state.jobs.map((job, index) => (
                <Col style={{ padding: 20 }}>
                  <Card text="white" bg="dark" style={styles.card}>
                    <Card.Body>
                      <Card.Title>
                        <Link to={`${this.url}/${job.jobId}`}>
                          {job.jobTitle}
                        </Link>
                      </Card.Title>
                    </Card.Body>
                  </Card>
                </Col>
              ))}
            </Row>
          </Container>
        </Container>
      </BrowserRouter>
    );
  }
}

export default Want;

正在消失的作业组件

export class Job extends Component {
  render() {
    return <p>this will disappear</p>;
  }
}

完整的代码沙盒链接

https://codesandbox.io/s/mystifying-yalow-6jcyn?fontsize=14&hidenavigation=1&theme=dark

当我点击软件链接时,卡片应该会消失,但不是image 但到目前为止,工作组件正在出现并且工作正常 但是当我刷新页面时,job 组件消失了,点击 software link 它以一种奇怪的方式扩展了 url。 component disappers

【问题讨论】:

  • 请在问题本身中包含minimal reproducible example,而不仅仅是在 Codesandbox 之类的场外服务上(尽管它仍然可以作为附加参考链接)。
  • componentWillMount 已弃用,您使用的是哪个版本的 React?
  • 并且使用this.url 来保留prop 值是一种不好的做法,并且可能已经引起了问题。直接在render 中使用prop 值。 const url = this.props.location.pathname
  • 移除了componentWillMount,直接使用this.props.location.pathname,对实际问题没有帮助

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


【解决方案1】:

因为want.js中的这一行而发生这种情况

<Route path={`${this.props.location.pathname}/:jobId`} component={Job} />

每次重新加载浏览器时,它都会将 ID 添加到路径名 /JobPortal/Want/1 的末尾,即 /JobPortal/Want/1/1/JobPortal/Want/1/1/1,因此您会不断更改与路由匹配的路径。

改成

<Route path={`${this.props.match.path}/:jobId`} component={Job} />

我也会更明确地使用您的链接,因为它还会在每次点击时将自身复制到路径上:

<Link to={`/JobPortal/Want/${job.jobId}`}>
 {job.jobTitle}
</Link>

像这样使用this.props.location.pathname 时要小心,因为它包含您的params

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2018-01-07
    • 1970-01-01
    • 2021-04-03
    • 2020-12-22
    • 2021-08-19
    相关资源
    最近更新 更多