2차 프로젝트 -기억에 남는 코드

Perfume·2020년 11월 15일
0
  • 사용자가 답변을 누르면 다음 질문으로 넘어가고, 마지막 질문에 대답하면 그동안 응답했던 답변들을 모아 백으로 보내주는 로직
  handleAnswer = (title) => {
    this.setState(
      {
        answers: [...this.state.answers, title],
        answerIdx: this.state.answerIdx + 1,
      },
      () => {
        if (this.state.answerIdx === 5) {
          fetch(`${KM_URL}/products/recommend`, {
            method: "POST",
            body: JSON.stringify(this.state),
            headers: {
              "Content-Type": "application/json",
            },
          })
            .then((res) => res.json())
            .then((res) =>
              this.props.history.push(`/productdetails/${res.foundProductID}`)
            );
        } else this.props.history.push(`/${this.state.answerIdx}`);
      }
    );
  };
  • 위의 질문의 경우, 어떤 답을 눌러도 다음 질문이 동일하기 때문에 질문이 몇 가지 되지 않아 굳이 백으로부터 데이터를 받을 필요성이 없었다. 그래서 mock data처럼 프론트의 선에서 관리하는 데이터를 만든 다음, 그것을 연결해서 사용했다. 이 과정에서 내가 원하는 데이터만 선별해서 보일 수 있도록 filter를 처음으로 사용해봤는데 그 점이 인상 깊어서 기록해둔다.
  componentDidMount() {
    const { quizNums } = this.props.match.params;
    fetch(`http://localhost:3000/Data/Quizdata.json`)
      .then((Quizdata) => Quizdata.json())
      .then((Quizdata) =>
        this.setState({
          quiz_data: Quizdata.quiz_data.filter(
            (el) => el.id === Number(quizNums)
          ),
        })
      );
  }

  componentDidUpdate(prevProps) {
    const { quizNums } = this.props.match.params;
    const prevId = prevProps.match.params.quizNums;
    if (quizNums !== prevId) {
      fetch(`http://localhost:3000/Data/Quizdata.json`)
        .then((Quizdata) => Quizdata.json())
        .then((Quizdata) => {
          this.setState({
            quiz_data: Quizdata.quiz_data.filter(
              (el) => el.id === Number(quizNums)
            ),
          });
        });
    }
  }
  • 다른 분들이 만든 컴포넌트를 불러서 사용했는데, 외적인 부분(?)만 불려오고 다른 기능이 전혀 작동하지 않았다. 도대체 뭐가 문제인지 몰라 고민했는데 경민님이 앞에 this를 붙여 주시니 마법처럼 해결되었다... 이 코드의 경우 더 공부해보고 싶어서 남겨둔다.
        <div className="loginModal">
          {this.state.showLogin && (
            <>
              <div className="loginBar">
                <Login showLoginModal={this.showLoginModal} />
              </div>
              <LoginModal />
            </>
          )}
        </div>
        <div className="CartModal">
          {this.state.showCart && (
            <>
              <Cart
                handleHideCart={this.handleHideCart}
                handleShowCart={this.handleShowCart}
              />
            </>
          )}
        </div>
profile
공부하는 즐거움

0개의 댓글