0

Не понимаю как можно сделать несколько страниц с контентом не создавая при этом отдельной папки для каждой страницы и повторять все те же функции, если на каждой странице меняется только один компонент,как поступить?

Вот app.js

class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route path='/detective' component={BooksGenre}/>
          <Route path='/humor' component={BooksGenre}/>
          <Route path='/fantasy' component={BooksGenre}/>
          <Route path='/poetry' component={BooksGenre}/>
          <Route path='/loveStory' component={BooksGenre}/>
          <Route path='/childrens' component={BooksGenre}/>
          <Route path='/business' component={BooksGenre}/>
          <Route path='/adventure' component={BooksGenre}/>
          <Route path='/cart' component={Cart}/>
        </Switch>
      </BrowserRouter>
    );
  }
}

export default App;

Вот сама страница в которой нужно менять только передаваемое в <BooksCollection/>, a именно collectionName='News' collection={this.NewList()}

    class BooksGenre extends React.Component {
      constructor(props) {
        super(props);
        this.ClickMenu = this.ClickMenu.bind(this);
        this.getStateSignIn = this.getStateSignIn.bind(this);
        this.getStateSignUp = this.getStateSignUp.bind(this);
      }

          state = {
            menuFlag: false,
            modalFlag: false,
            signIn: false,
            signUp: false
          }

          ClickMenu() {
            this.setState({ menuFlag: !this.state.menuFlag });
          }

          openCloseScreen = () => {
            this.setState({ modalFlag: true });
          }

          closeScreen = () => {
            this.setState({ modalFlag: false });
          }

          NewList() {
            return this.props.collection.map((book) => {
              if (book.genre === 'detectiv') {
                return (
                  <Book lol={() => this.props.add(book)} key={book.id} name={book.nameBook} price={book.priceBook} img={book.imgBook} description={book.description} callBack={this.openCloseScreen} close={this.closeScreen}/>
                );
              } return false;
            });
          }

          InterestingList() {
            return this.props.collection.map((book) => {
              if (book.interesting === 'yes') {
                return (
                  <Book key={book.id} name={book.nameBook} price={book.priceBook} img={book.imgBook} description={book.description} callBack={this.openCloseScreen} close={this.closeScreen}/>
                );
              } return false;
            });
          }

          getStateSignIn() {
            this.setState({ signIn: !this.state.signIn });
          }

          getStateSignUp() {
            this.setState({ signUp: !this.state.signUp });
          }

          render() {
            return (
              <div>
                <div className={`${this.state.menuFlag === true || this.state.modalFlag === true || this.state.signIn === true || this.state.signUp === true ? 'closeScreen' : ''}`}
                  onClick={() => {this.setState({ menuFlag: false });}}/>
                <Header menuClick={this.ClickMenu} getIn={this.getStateSignIn} getUp={this.getStateSignUp} count={this.props.cart.length}/>
                <Menu stateMenu={this.state.menuFlag}/>
                <BooksCollection collectionName='News' collection={this.NewList()}/>
                <Interesting interestingName={'Interesting'} collection={this.InterestingList()}/>
                <Footer />
              </div>
            );
          }
    }

    function bookStateToProps(state) {
      return {
        collection: state.collection,
        cart: state.cart
      };
    }

    function matchDispatchToProps(dispatch) {
      return bindActionCreators({ add: addBook }, dispatch);
    }

    export default connect(bookStateToProps, m

atchDispatchToProps)(BooksGenre);

1 ответ 1

0
  1. Можно взять данные из роутинга, которые можно получить через props.match, в компоненте <BooksGenre />. Пример объекта match:

{ path: "/detective", url: "/detective", isExact: true, params: {} };

  1. Можно передавать custom prop, для каждого из роутов:
class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path='/' component={Home}/>
          <Route path='/detective' render={() => <BooksGenre genre="detective" />} />
          <Route path='/humor' render={() => <BooksGenre genre="humor" />} />
          <Route path='/fantasy' render={() => <BooksGenre genre="fantasy" />} />
          ...
        </Switch>
      </BrowserRouter>
    );
  }
}
export default App;

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.