React — рефакторинг кода с IF и Else

avatar
jamal
1 июля 2021 в 20:59
101
2
-1

Я изучаю реакцию и разработал некоторую логику для рендеринга DIV, но я знаю, что это избыточно, и я не знаю, как именно его реорганизовать. Это код:

renderHeader() {
const {
  course_module_index
} = this.state;
if(course_module_index === 0)
return (
  <>
    <h4 className="col-3 md-col-8 sm-col-4 color__primary1 bold">Conversation</h4>
    <p className="col-8 offset-3 md-col-8 sm-col-4 body2 back__type">
      Practice your English in the conversation classes available in the schedule below. you can enter a
      class up to 10 min. after your start time, but we recommend that you book a time as
      class size is limited.
    </p>
    <div className="header__opening-class">
      <h6> Opening Classes Available!</h6>
      <p> Mon/Wed/Fri from 9:00h to 9:30h | Tues/Thurs from 7:00 pm to 7:30 pm </p>
    </div>
    <hr ref={this.conversationBlockRef} className="margin-zero col-12 md-col-8 sm-col-4" />
  </>
);
return (
  <>
    <h4 className="col-3 md-col-8 sm-col-4 color__primary1 bold">Conversation</h4>
    <p className="col-8 offset-3 md-col-8 sm-col-4 body2 back__type">
      Practice your English in the conversation classes available in the schedule below. you can enter a
      class up to 10 min. after your start time, but we recommend that you book a time as
      class size is limited.
    </p>
    <hr ref={this.conversationBlockRef} className="margin-zero col-12 md-col-8 sm-col-4" />
  </>
);

Источник
Dave Newton
1 июля 2021 в 21:03
0

Если единственная разница в том, что header__opening-class div кажется условным рендерингом, было бы достаточно, хотя трудно понять, является ли это единственным изменением.

Rick Stanley
1 июля 2021 в 21:05
0

Я думаю, что этот вопрос лучше опубликовать n codereview.stackexchange.com, при этом вы всегда можете использовать тернарный оператор для такого сценария, например: return your_condition ? <></> : <></>

surendrapanday
2 июля 2021 в 00:45
0

Пожалуйста, четко опишите, какой раздел вы пытаетесь отобразить с условием и какой раздел вы пытаетесь отобразить по умолчанию? Не очень понятно в вашем вопросе.

Ответы (2)

avatar
Stephen Jennings
1 июля 2021 в 21:05
1

Элементы React можно хранить в переменной, чтобы их можно было использовать позже, и вы можете использовать условие, чтобы решить, отображать ли элемент

  renderHeader() {
    const { course_module_index } = this.state;

    // use a condition to conditionally render this element
    const schedule = course_module_index === 0 && (
      <div className="header__opening-class">
        <h6>Opening Classes Available!</h6>
        <p>
          Mon/Wed/Fri from 9:00h to 9:30h | Tues/Thurs from 7:00 pm to 7:30 pm
        </p>
      </div>
    );

    // Use the schedule variable within the following expression.
    // If `schedule` is false, then React will render nothing in its place
    return (
      <>
        <h4 className="col-3 md-col-8 sm-col-4 color__primary1 bold">
          Conversation
        </h4>
        <p className="col-8 offset-3 md-col-8 sm-col-4 body2 back__type">
          Practice your English in the conversation classes available in the
          schedule below. you can enter a class up to 10 min. after your start
          time, but we recommend that you book a time as class size is limited.
        </p>
        {schedule}
        <hr
          ref={this.conversationBlockRef}
          className="margin-zero col-12 md-col-8 sm-col-4"
        />
      </>
    );
  }

Если вам легче читать, вы можете использовать условие непосредственно внутри JSX:

  renderHeader() {
    const { course_module_index } = this.state;

    return (
      <>
        <h4 className="col-3 md-col-8 sm-col-4 color__primary1 bold">
          Conversation
        </h4>
        <p className="col-8 offset-3 md-col-8 sm-col-4 body2 back__type">
          Practice your English in the conversation classes available in the
          schedule below. you can enter a class up to 10 min. after your start
          time, but we recommend that you book a time as class size is limited.
        </p>
        {course_module_index === 0 && (
          /* This won't render if the condition was false */
          <div className="header__opening-class">
            <h6>Opening Classes Available!</h6>
            <p>
              Mon/Wed/Fri from 9:00h to 9:30h | Tues/Thurs from 7:00 pm to 7:30
              pm
            </p>
          </div>
        )}
        <hr
          ref={this.conversationBlockRef}
          className="margin-zero col-12 md-col-8 sm-col-4"
        />
      </>
    );
  }
avatar
surendrapanday
2 июля 2021 в 01:51
1

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

Ссылка: https://codesandbox.io/embed/old-haze-t3w1w?fontsize=14&hidenavigation=1&theme=dark

import { useEffect, useState } from "react";
import "./styles.css";

import "./styles.css";

export default function App() {
  const [moduleIndex, setModuleIndex] = useState(null);

  useEffect(() => {
    setModuleIndex(1);
  });
  const _renderHeader = () => {
    return (
      <>
        {moduleIndex ? (
          <div className="header__opening-class">
            <h6> Opening Classes Available!</h6>
            <p>
              {" "}
              Mon/Wed/Fri from 9:00h to 9:30h | Tues/Thurs from 7:00 pm to 7:30
              pm{" "}
            </p>
          </div>
        ) : null}
        <h4 className="col-3 md-col-8 sm-col-4 color__primary1 bold">
          Conversation
        </h4>
        <p className="col-8 offset-3 md-col-8 sm-col-4 body2 back__type">
          Practice your English in the conversation classes available in the
          schedule below. you can enter a class up to 10 min. after your start
          time, but we recommend that you book a time as class size is limited.
        </p>
        <hr
          ref={this.conversationBlockRef}
          className="margin-zero col-12 md-col-8 sm-col-4"
        />
      </>
    );
  };

  return <div className="App">{_renderHeader()}</div>;
}