본문 바로가기
Web/React

laka project3 for in & concat & localStorage & toLocaleString & fetch 주소 & 수량과 합계

by 긴모양 2020. 6. 28.

20.06.02 for in & concat

for in

객체의 프로퍼티명을 열거하는 반복문 for문과 동일하지만 for문보다 간단하게 작성이 가능하다.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for(let i=0; arr.length>i; i++){
  console.log(i)
}

for(let i in arr) {
    console.log(i)
}

//console.log의 결과값은 동일하다.

javascript for in 문

 

Concat

기존의 배열에 내가 추가하고 싶은 값을 추가해서 리턴해주는 method

const arr = [1, 2, 3, 4, 5]
const newArr = arr.concat(['일', '이', '삼', '사', '오'])
console.log(newArr)

_2020-06-06__9 48 02

imgClick = (colors) => {
        const { wishList } = this.state;
        console.log("wishList : ", wishList)
        console.log(colors)
        if (wishList.includes(colors)) {
            alert("이미 선택되어 있는 옵션입니다.");
        } else {
            this.setState({
                **wishList: wishList.concat(colors)**
                                //wishList에 담기는 값들이 계속 수정이 되기 때문.
            })
        }
    }

Array.prototype.concat()



20.06.04 localStorage & toLocaleString & fetch 주소 & 수량과 합계

fetch시 localStorage.setItem으로 토큰값 받아오기

goMain = () => {
        fetch(`${API}/member/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                nickname: this.state.id, //BE와 상의하에 키 값 정하기
                password: this.state.pw,
            })
        })
            .then(response => {
                if (response.status === 200) return response.json() //response.json()을 하고 다음 .then을 돈다
                else throw Error; //else면 에러를 던지는거야
            })
            .then(response => {
                console.log(response)
                if (response.token) {
                    localStorage.setItem('Authorization', response.token);
                    //login시 유저의 정보를 알 수 있는 token값을 받아온다. 'Authorization'은 내가 정할 수 있는 key값. response의 token은 BE에서 정해주는 토큰
                    this.props.history.push("/");
                }
            })
            .catch(error => alert("ERROR")) //else에서 던진 에러를 받아서 alert처리를 한다.
}

참고사이트

LocalStorage, sessionStorage / Storage.setItem()

localStorage의 token값을 활용한 로그인 & 로그아웃 버튼

_2020-06-06__4 34 52_2020-06-06__4 35 10

this.state = {
      login: "LOGIN",
      join: true,
      scrollTop: {},
      navClass: "header",
    };

componentDidMount() {
    window.addEventListener("scroll", this.onScroll);
    if ("Authorization" in localStorage) { //localStorage에 token이 존재하면
      this.setState({
        login: "LOGOUT",
        join: false,
      });
    }
  }

loginEvent = () => {
  if (this.state.login === "LOGOUT") {
    this.props.history.push("/signin");
    localStorage.clear("Authorization"); //token을 삭제해준다.
    this.setState({
      login: "LOGIN",
      join: true,
    });
  } else {
    this.props.history.push("/signin");
  }
};

<span onClick={this.loginEvent}>
  {login} //logout상태일 땐 login, login상태일 땐 logout
</span>
<span
  style={{ display: join ? 'inlineblock' : 'none' }}
  onClick={(e) => {
    this.props.history.push("/signup");
  }}>
  JOIN
</span>

참고사이트

ReactJS Login / Log Out toggle button using states / javascript - 변수의 값이 localStorage에 있는지 확인하십시오.

비동기에서 값을 아직 못받아왔다면?

//ProductDetailMyTop

<div className="ProductDetailTop">
  {this.props.colorInfo.price_krw && ( 
            /*price_krw가 값이 있다면 모든 데이터에 값이 들어온 상황이니 하나의 조건만 걸어줘도 괜찮다. 
                굳이 .name까지 찾아줄 필욘 없다.*/
  <main>
      <div className="mainLeft">
          <div className="mainLeftTitle" >
                <h1>{this.props.colorInfo.name}</h1>
                <span>{this.props.colorInfo.description}</span>
                <span className="price">
                    KRW {Number(this.props.colorInfo.price_krw).toLocaleString()}
                    // price_krw가 string이기에 number로 변환해준다.
                </span>
          </div>

 

사용된 함수


toLocaleString : 숫자의 로케일 특정 숫자 표현으로 변환해 문자열로 리턴하는데 사용된다. 아래의 이미지에서 Json파일에는 18000.00로 담겨있지만 이를 해결 하기 위해서 toLocaleString함수를 사용해서 소숫점 앞의 값만 사용해준다.

_2020-06-06__4 47 17

number.toLocaleString([locale [, options]]);
<span className="price">KRW {Number(this.props.colorInfo.price_krw).toLocaleString()}</span>

참고사이트

JavaScript: Number toLocaleString() method Number.prototype.toLocaleString()

fetch의 링크

config.js

export const API = `http://데이터 받아올 링크`;
import { API } from “../../config”;

fetch(`${API}/order`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: token //헤더에서 토큰을 보내는 것 
            },
            body: JSON.stringify({
                id: this.props.colorInfo.id,
                wishList: this.state.wishList.order_quantity.name,
            })

수량 카운트


minusButton = (idx) => { //idx가 곧 wishList에 담긴 순서를 알 수 있다.
        const newWishList = [...this.state.wishList]; //wishList를 clone한다. 값(수량)이 변해야하기에
        console.log("새로운 리스트", newWishList);

        if (newWishList[idx].order_quantity === 1) {
            alert("최소 주문수량은 1개 입니다.")
        } else {
            newWishList[idx].order_quantity--;
            this.setState({ wishList: newWishList });
        }
    };

    plusButton = (idx) => {
        const newWishList = [...this.state.wishList];

        if (newWishList[idx].order_quantity > 0) {
            newWishList[idx].order_quantity++;
            this.setState({ wishList: newWishList });
        }
    };

합계 구하기

//수정하기 전 코드
sumTotal = () => {
    let sum = 0;
    this.state.wishList.map((item) => {
    sum += 18000 * item.order_quantity
    return sum
       })
    this.setState({
    total: sum
    })
}

//수정한 코드
sumTotal = () => {
      let sum = 0;
      for (let i in this.state.wishList) {
          sum += this.state.wishList[i].order_quantity
      }
      return sum;
}

<span className="price">KRW {this.sumTotal() * this.props.colorInfo.price_krw}</span>

fetch json input 오류

//SignIn

.then(response => response.json())
.then(response => { console.log(response);
    if (response.token) {
        localStorage.setItem('Authorization', response.token);
        this.props.history.push("/");
        } 
        else {
        alert("로그인 정보를 확인해주세요.") //이 부분에서 에러가 발생한다. 그 이유는 아무런 값을 받지 못했다.
        }
});

goMain = () => {
  fetch(`${API}/member/login`, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          nickname: this.state.id,
          password: this.state.pw,
      })
  })
  .then(response => {
      if (response.status === 200) return response.json() //response.json()을 하고 다음 .then을 돈다
      else throw Error; //else면 에러를 던지는거야
  })
  .then(response => {
      console.log(response)
      if (response.token) {
          localStorage.setItem('Authorization', response.token);
          this.props.history.push("/");
      }
  })
  .catch(error => alert("ERROR")) //else에서 던진 에러를 받아서 alert처리를 한다.
}

.then & .catch & .throw에 대해서 자세히 알아보기

Fetch from an API and Display Some Pictures: React /
Learn how to handle JavaScript Errors with Try, Throw, Catch, & Finally /
(HTML&DOM) Fetch API /
JavaScript Errors Try Catch Throw /
Error handling, "try..catch" /
JavaScript Try Catch: Exception Handling Explained

댓글