React Router 4: внутренняя навигация изменяет URL, но не просматривает - PullRequest
0 голосов
/ 07 октября 2018

Я довольно новичок в React и застрял в проблеме с React Router 4, которую не могу решить, даже после просмотра всех вопросов по этой теме.У меня есть раздел навигации в середине моей страницы, который должен переключать вид внизу страницы в зависимости от того, что я нажал.Когда я щелкаю новый раздел на панели навигации, URL-адрес меняется на правильный, но мое представление не обновляется, а просто остается пустым.Что-то не так с моим кодом, вызывающим эту проблему?См. Ниже:

Моя главная панель навигации вверху страницы (которая работает) можно увидеть здесь:

import React, { Component } from "react";
import { Menu, Container, Button, Icon } from "semantic-ui-react";
import { NavLink, Link, withRouter } from 'react-router-dom'
import "semantic-ui-css/semantic.min.css";

class NavBar extends Component {
  render() {
    return (
      <Menu inverted fixed="top">
        <Container>
          <Menu.Item as={Link} to="/" header>
            <Icon name="angle double up" size="big" />
            Atlas
          </Menu.Item>
          <Menu.Item as={NavLink} to="/profile" name="Profile" />
          <Menu.Item as={NavLink} to="/budget" name="Budget" />
          <Menu.Item position="right">
            <Button as={Link} to="/settings" color="brown" animated="vertical">
              <Button.Content hidden>Settings</Button.Content>
              <Button.Content visible>
                <Icon name="setting" />
              </Button.Content>
            </Button>
            <Button as={Link} to="/proSignUp" color="brown" animated="fade">
              <Button.Content visible>Sign-up for a Pro Account</Button.Content>
              <Button.Content hidden>$5 a month</Button.Content>
            </Button>
          </Menu.Item>
        </Container>
      </Menu>
    );
  }
}

export default withRouter(NavBar);

Файл My App.jsx (работает), который содержит панель навигации и маршруты:

import React, { Component } from "react";
import { Container } from "semantic-ui-react";
import { Route, Switch } from "react-router-dom";
import ProfileDashboard from "../../features/profile/ProfileDashboard/ProfileDashboard";
import NavBar from "../../features/nav/NavBar/NavBar";
import HomePage from "../../features/home/HomePage";
import BudgetDashboard from "../../features/budget/BudgetDashboard/BudgetDashboard";
import SettingsPage from "../../features/settings/Settings"
import ProSignUp from "../../features/proSignUp/ProSignUp";

class App extends Component {
  render() {
    return (
      <div>
        <Switch>
          <Route exact path="/" component={HomePage} />
        </Switch>

        <Route
          path="/(.+)"
          render={() => (
            <div>
              <NavBar />
              <Container className="main">
                <Switch>
                  <Route path="/profile" component={ProfileDashboard} />
                  <Route path="/budget" component={BudgetDashboard} />
                  <Route path="/settings" component={SettingsPage} />
                  <Route path="/proSignUp" component={ProSignUp} />
                </Switch>
              </Container>
            </div>
          )}
        />
      </div>
    );
  }
}

export default App;

Навбар страницы моего профиля (который меняет маршруты) можно посмотреть здесь:

import React from "react";
import { Grid, Menu } from "semantic-ui-react";
import { NavLink, withRouter } from 'react-router-dom'

const ProfileNav = () => {
  return (
    <Grid.Column width={16}>
      <Menu horizontal="true" secondary>
        <Menu.Item as={NavLink} to="/profile/overview">Overview</Menu.Item>
        <Menu.Item as={NavLink} to="/profile/analytics">Analytics</Menu.Item>
      </Menu>
    </Grid.Column>
  );
};

export default withRouter(ProfileNav);

И, наконец, мою ProfileDashboard (которая не работает), которая содержит панель навигации моего профиля и маршруты, можно увидеть ниже:

import React, { Component } from "react";
import { Grid, Divider } from "semantic-ui-react";
import { Switch, Route, Redirect } from "react-router-dom";
import ProfileHeader from "../ProfileHeader/ProfileHeader";
import ProfileNav from "../ProfileNav/ProfileNav";
import ProfileList from "../ProfileList/ProfileList";
import ProfileAnalytics from "../ProfileAnalytics/ProfileAnalytics";

const contentHash = {
  headerContent: [
    {
      title: "Demographics",
      age: 21,
      sex: "male",
      location: "Tucky, KY"
    },
    {
      title: "Profession",
      jobTitle: "Event Coordinator",
      employer: "Tucky Tuck",
      experience: "5 years",
      preTaxIncome: 62000,
      postTaxIncome: 44000
    },
    {
      title: "Investments",
      highRisk: "blah blah",
      mediumRisk: "blah blah",
      lowRisk: "blah blah"
    },
    {
      title: "Retirement",
      "401k": 415000,
      RothIRA: 61000
    }
  ]
};

class ProfileDashboard extends Component {
  render() {
    return (
      <Grid>
        <Grid.Column width={16}>
          <ProfileHeader headerContent={contentHash.headerContent} />
          <Divider />
          <ProfileNav />
          <Switch>
            <Redirect exact from="/profile" to="/profile/overview" />
            <Route path="profile/overview" component={ProfileList} />
            <Route path="profile/analytics" component={ProfileAnalytics} />
          </Switch>
        </Grid.Column>
      </Grid>
    );
  }
}

export default ProfileDashboard;

1 Ответ

0 голосов
/ 07 октября 2018

Я понял это после многих проб и ошибок.Мне пришлось поместить оба компонента, между которыми я переключался, в новый компонент, чтобы маршрутизация работала.Поэтому я создал новый компонент ProfileFooter, который содержал всю логику маршрутизации и переключался между страницами ProfileList и ProfileAnalytics.

import React, { Component } from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import ProfileList from "../ProfileList/ProfileList";
import ProfileAnalytics from "../ProfileAnalytics/ProfileAnalytics";

class ProfileFooter extends Component {
  render() {
    return (
      <div>
        <Switch>
          <Redirect exact from="/profile" to="/profile/overview" />
          <Route path="/profile/overview" component={ProfileList} />
          <Route path="/profile/analytics" component={ProfileAnalytics} />
        </Switch>
      </div>
    );
  }
}

export default ProfileFooter;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...