我有一个嵌套的路由组件,它会显示在父组件的底部。我想在新页面中显示此组件。这是我的代码 -
CategoryList.js
class CategoryList extends Component {
state = {
categories: []
}
componentDidMount() {
fetch('http://localhost:8080/testcategory')
.then(results => {
return results.json();
}).then(data => {
this.setState({ categories: data.categories });
})
.catch(error => {
this.setState({ error: true });
});
}
categorySelectedHandler = (id) => {
this.props.history.replace('/testcategory/' + id);
}
render() {
let categories = <p style={{ textAlign: 'center' }}>Something went wrong!</p>;
if (!this.state.error) {
categories = this.state.categories.map(category => {
{this.props.children}
return (
<Table.Row key={category.id}>
<Table.Cell>{category.name}</Table.Cell>
<Table.Cell>{category.id}</Table.Cell>
<Table.Cell> <Button icon labelPosition='left' onClick={() => this.categorySelectedHandler(category.id)}>show</Button></Table.Cell>
{/* Tried this as well
<Table.Cell>
<Link to={"/category/"+category.id}>
<Button icon labelPosition='left' >Show</Button>
</Link>
</Table.Cell> */}
</Table.Row>
)
})
}
return (
<div>
<Table stackable>
<Table.Header>
<Table.Row >
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>ID</Table.HeaderCell>
<Table.HeaderCell>Operations</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{categories}
{this.props.children}
</Table.Body>
</Table>
<Route path={this.props.match.url + '/:id'} exact component={CategoryDetails} />
</div>
);
}
}
export default CategoryList;
CategoryDetails.js
import React, { Component } from 'react';
import './CategoryDetails.css';
class CategoryDetails extends Component {
state = { loadedCategory: null }
componentDidMount() {
this.loadData();
}
componentDidUpdate() {
this.loadData();
}
shouldComponentUpdate(nextProps, nextState) {
return nextProps.match.params.id != nextState.loadedCategory.id ;
}
loadData=() =>{
if (this.props.match.params.id) {
if (!this.state.loadedCategory || (this.state.loadedCategory && this.state.loadedCategory.id !== +this.props.match.params.id)) {
fetch('http://localhost:8080/testcategory/' + this.props.match.params.id)
.then(results => {
return results.json();
}).then(data => {
this.setState({ loadedCategory: data});
})
.catch(error => {
this.setState({ error: true });
});
}
}
}
render() {
let category = <p style={{ textAlign: 'center' }}>Please select a Post!</p>;
if (this.props.match.params.id) {
category = <p style={{ textAlign: 'center' }}>Loading...!</p>;
}
if (this.state.loadedCategory) {
category = (
<div className="CategoryDetails">
<h1>{this.state.loadedCategory.name}</h1>
<p>{this.state.loadedCategory.code}</p>
<p>{this.state.loadedCategory.id}</p>
{this.props.children}
</div>
);
}
return (category);
}
}
export default CategoryDetails;
答案 0 :(得分:2)
从CategoryList文件中删除CategoryDetails
路由并将其移动到为CategoryList
指定Route的文件
<Route path={this.props.match.url + '/:id'} exact component={CategoryDetails} />
<Route path={this.props.match.url + '/:dummyid'} exact component={CategoryList} />