Проблемы при переходе по URL-адресу, например "/ annotationsList /: id" - PullRequest
0 голосов
/ 12 января 2019

Я пытаюсь перейти от списка аннотаций к конкретной аннотации, используя ссылку из React Router. Но он не рендерил компонент.

Итак, у меня есть AnnotationList, в котором есть все аннотации. Каждая аннотация имеет "". В моем Container.js я объявил маршрут следующим образом:

<Route path="/annotationList/annView/:id" component={annView} />

И в том же контейнере у меня есть компонент annView:

const annView = ({ match }) => {
    const { id } = match.params;
    console.log(id);
    return(
        <AnnotationView id={id} />
    )
}

Когда я нажимаю на ссылку, URL меняется на правильный, но ничего не отображается. Что я делаю не так?

Я вставлю полный код этих двух файлов js, если это поможет.

Container.js

import React from 'react';
import { Route, Switch, withRouter, Link } from "react-router-dom";
import ProductList from './List/ProductList';
import CustomersList from './List/CustomersList';
import AppointmentsList from './List/AppointmentsList';
import AnnotationList from './List/AnnotationList';
import AddProduct from './Post/AddProduct';
import '../styles/App.css';
import AnnotationView from './Item/AnnotationView';

function Container({ location }) {
    return (
        <div>
            <Switch location={location}>
                <Route path="/productsList" component={ProductList} />
                <Route path="/customersList" component={CustomersList} />
                <Route path="/appointmentsList" component={AppointmentsList} />
                <Route path="/annotationList" component={AnnotationList} />
                <Route path="/annotationList/annView/:id" component={annView} />
                <Route path="/addProduct" component={AddProduct} />
            </Switch>
        </div>
    );
}

const annView = ({ match }) => {
    const { id } = match.params;
    console.log(id);
    return(
        <AnnotationView id={id} />
    )
}

export default withRouter(Container);

import React, { Component } from 'react';
import { Table } from 'reactstrap';
import { Link } from 'react-router-dom';
import AnnotationView from '../Item/AnnotationView';

class AnnotationList extends Component {
    constructor(props) {
        super(props);

        this.state = {
            annotations: [],
            isLoading: false
        }

    }

    componentDidMount() {
        this.setState({isLoading: true});
        fetch('http://localhost:8080/annotations')
        .then(response => response.json())
        .then(data => this.setState({annotations: data, isLoading: false}));
    }

    render() {
        const { annotations, isLoading } = this.state;

        if(isLoading) {
            return <p>Loading...</p>;
        }

        return(
            <div>
                <h2>Anotaciones</h2>
                <div className="form-group">
                    <input type="date"/>
                </div>
                <Table>
                    {annotations.map((ann) =>
                        <div>
                            <tr>
                                <Link to={`/annotationsList/annView/${ann.id}`}>
                                    <th>{ann.name}</th>
                                </Link>
                            </tr>
                            <tr>
                                <td>{ann.text}</td>
                            </tr>
                        </div>
                    )}
                </Table>
            </div>
        )
    }
}

export default AnnotationList;

Заранее спасибо.

1 Ответ

0 голосов
/ 12 января 2019

У вас есть опечатка в вашем Link компоненте.

Вы пытаетесь найти соответствие этому маршруту <Route path="/annotationList/annView/:id" component={annView} />

но у вашего Link есть annotations с с /annotationsList/annView/anythingHere

Вы должны изменить свой Link Компонент на это:

<Link to={`/annotationList/annView/${ann.id}`}>
  <th>{ann.name}</th>
</Link>

Примечание: Я бы по-прежнему рекомендовал, чтобы каждый раз, когда у вас были похожие маршруты, вы использовали exact хотя бы на одном из них, чтобы React Router знал, как различать маршруты.

function Container({ location }) {
    return (
        <div>
            <Switch location={location}>
                <Route path="/productsList" component={ProductList} />
                <Route path="/customersList" component={CustomersList} />
                <Route path="/appointmentsList" component={AppointmentsList} />
                <Route exact path="/annotationList" component={AnnotationList} />
                <Route path="/annotationList/annView/:id" component={annView} />
                <Route path="/addProduct" component={AddProduct} />
            </Switch>
        </div>
    );
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...