React Router - изменяет URL, но не отображает и не обновляет компонент - PullRequest
0 голосов
/ 07 января 2020

Это страница блога, над которой я работал, я извлекаю из API, который возвращает это: https://imgur.com/uHw59Gp

Я извлекаю API из приложения. js , отправьте реквизиты Navcontent

import React from "react";
import "../css/App.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Inicio from "../views/Inicio";
import BlogPost from "../views/BlogPost";
import AllPosts from "../views/AllPosts";
import Footer from "../components/Footer";
import CategoryPosts from "../views/CategoryPosts";
import axios from 'axios';

import Navcontent from './Navcontent';
import Navigation from './Navigation/Navigation';


class App extends React.Component {
  state = {
    section:[]
  };

  componentDidMount() {
    fetch('http://localhost:8082/api/inicio')
      .then(res => res.json() )
      .then(data => {
        if(data){
          let datosArticuloInicio = data.data[9]
          this.setState({
            section: datosArticuloInicio
          }); 
        } 
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div className="App" style={{height: '100%'}}>
        <BrowserRouter>
        <Navcontent section={this.state.section}></Navcontent>
          <Switch>
            <Route exact path="/" component={Inicio} />
            <Route exact path="/articulo/undefined" component={Inicio} />
            <Route exact path="/seccion/:section" component={CategoryPosts} />
            <Route exact path="/inicio/all" component={AllPosts} />
            <Route path="/articulo/:articuloId" component={BlogPost} />
            <Route render={() => <div>404 Not Found</div>} />
          </Switch>
        </BrowserRouter>
        <Footer></Footer>
      </div>
    )
  }
}


export default App;

Navcontent возьмите реквизиты и создайте ссылку для каждого пропра (кнопка AKA) и верните ее в приложение. js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from '@material-ui/core/AppBar';
import Toolbar from "@material-ui/core/Toolbar";
import { Link as Link2 } from 'react-router-dom';
import Button from '@material-ui/core/Button';

import '../css/Navcontent.css';
import DrawerToggleButton from './SideDrawer/DrawerToggleButton';

const useStyles = makeStyles(theme => ({
  toolbar: {
    borderBottom: `1px solid ${theme.palette.divider}`
  },
  toolbarTitle: {
    flex: 1,
    width: "100% !important"
  },
  toolbarSecondary: {
    justifyContent: "space-between",
    overflowX: "auto",
    color: "black",

  },
  bg: {
    backgroundColor: "#4fa0cb",
    flexGrow: 1,
  },

  toolbarLink: {
    padding: theme.spacing(1),
    flexShrink: 0,
    color: "white",
    textDecoration: "none",
    fontFamily: "Roboto",
    '&:hover': {
      backgroundColor: 'rgb(122, 0, 118 )',
    },
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },

}));

export default function Navcontent(props) {
  const classes = useStyles();


  return (
    <div className={classes.bg}>
      <AppBar className={classes.bg} position="static">
        <Toolbar
          component="nav"
          variant="dense"
          className={classes.toolbarSecondary}
        >
      <div>
        <DrawerToggleButton/>
      </div>
          <Button component={Link2} className="navlink" to={`/`}>Inicio
          </Button>
          {props.section.map((section, id) => (
            <Button 
              component={Link2} 
              className="navlink"
              key={id}  
              to={`/seccion/${section.IdSection}`}
            >
              {section.Nombre}
            </Button>

          ))}
        </Toolbar>
      </AppBar>
    </div>
  );
}

this моя индексная страница https://imgur.com/HuAX4HI

, когда я нажимаю на навигационную ссылку, она отображает сообщения из раздела, на который нажали https://imgur.com/hKfVQLo

один раз в раздел, я пытаюсь нажать на другой раздел, но на этот раз URL-адрес меняется, но компонент не отображается. https://imgur.com/DsfO7wx

извините за длинный пост, но я не знаю, что вы делаете

...