我正在尝试使用来自React Router的链接从批注列表导航到具体的批注。但是它没有渲染组件。
因此,我有一个AnnotationList,其中包含所有注释。每个注释都有一个“”。在我的Container.js中,我这样声明了Route:
<Route path="/annotationList/annView/:id" component={annView} />
在同一个容器中,我有一个组件anView:
const annView = ({ match }) => {
const { id } = match.params;
console.log(id);
return(
<AnnotationView id={id} />
)
}
当我单击链接时,URL更改为正确的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;
谢谢。
答案 0 :(得分:1)
您的Link
组件中有一个错字。
您正在尝试匹配此路线
<Route path="/annotationList/annView/:id" component={annView} />
但是您的Link
的{{1}}带有 s
annotations
您必须将/annotationsList/annView/anythingHere
组件更改为此:
Link
注意:我仍建议您每次有类似的路由时,至少对其中1条使用<Link to={`/annotationList/annView/${ann.id}`}>
<th>{ann.name}</th>
</Link>
,以使React Router知道如何区分这些路由。>
exact