Показать вложенный компонент маршрута на новой странице - PullRequest
0 голосов
/ 07 мая 2018

У меня есть вложенный компонент маршрута, который отображается внизу родительского компонента. Я хочу отобразить этот компонент на новой странице. Вот мой код -

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;

1 Ответ

0 голосов
/ 07 мая 2018

удалить CategoryDetails Маршрут из файла CategoryList и переместить его в файл, где Маршрут указан для CategoryList

<Route path={this.props.match.url + '/:id'} exact component={CategoryDetails} />

<Route path={this.props.match.url + '/:dummyid'} exact component={CategoryList} />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...