728x90

✖ Installing Bundler error Your Ruby version is 2.6.10, but your Gemfile specified 2.7.5

ruby version error 해결 

//루비버전관리 프로그램 설치
brew install rbenv

//나는 mac 유저라서 터미널에서 바로 
code . 
//쳐주면 .zshrc파일 들어갈 수 있음. 접근해서 맨밑에 추가함
eval "$(rbenv init -)"

//원하는 버전 설치
rbenv install 2.7.5

//설치완료 확인 (이제는 자동으로 해줘서 안해도 되는 명령어라고 함)
rbenv rehash

//버전 변경 (이것도 자동으로 해주는 거같음 )
rbenv global 2.7.5

//버전확인 
ruby --version

//버전변경했는데도 자꾸 이전 버전이 뜬다면 터미널 껐다가 다시 버전체크해보자. 껐다 다시 킨 다음에야 나는 변경된 걸로 떴음

https://dololgun.github.io/macos/mac-ruby-reinstall/

 

MacOS ruby 버전 관리

mac에서 ruby버전 관리하기

dololgun.github.io

 

근데 ruby가 뭘까?

출처 : https://opentutorials.org/module/2878/16498

객체지향 언어인데 자유도가 있는 언어라고 한다

 

reactnative에서 ruby 쓰는 이유는 

Because iOS uses CocoaPods to handle dependencies which was written in Ruby

ios 가 cocoapods 사용하는데 이게 ruby로 쓰여서.

 

 

 

cocoapods 에러

https://reactnative.dev/docs/next/environment-setup

sudo arch -x86_64 gem install ffi
//이건 프로젝트 폴더 들어가서 cd ios 안에서 했다 pod install 해준 것
arch -x86_64 pod install

 

혹시몰라서 프로젝트 다 삭제하고 

npx react-native init AwesomeTSProject --template react-native-template-typescript

다시 하니 에러 없이 잘 됐다. 

 

 

 

아래글 초기셋팅 참고로 굿

https://zeunny.tistory.com/6

 

[React Native] 공식 문서 보고 Mac OS에서 개발 환경 설정하기

[React Native] 공식 문서 보고 Mac OS에서 개발 환경 설정하기 공식 문서는 아래 링크를 클릭해서 보면 된다. https://reactnative.dev/docs/environment-setup Setting up the development environment · React Native This page will h

zeunny.tistory.com

 

728x90
728x90

 

 

이메일링 서비스 구현을 위해서 

nodemailer 와 mailgun 을 알게 되었다.

 

 

nodemailer는

"Nodemailer is a module for Node.js applications to allow easy as cake email sending. "

Nodemailer는 케이크처럼 쉽게 이메일을 보낼 수 있도록 하는 Node.js 애플리케이션용 모듈입니다

https://nodemailer.com/about/

 

Nodemailer :: Nodemailer

Nodemailer Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default. npm i

nodemailer.com

 

 

mailgun

이메일전송 서비스 제공해주는 사이트

 

https://www.mailgun.com/

 

Transactional Email API Service For Developers | Mailgun

Powerful Transactional Email APIs that enable you to send, receive, and track emails, built with developers in mind. Learn more today!

www.mailgun.com

 

 

In short, SMTP is an open and established protocol with large ecosystem, while Mailgun API is better long term performance and maintenance wise.

요컨대, SMTP는 대규모 에코시스템을 갖춘 개방적이고 확립된 프로토콜인 반면 Mailgun API는 장기적 성능과 유지 관리 측면에서 더 좋습니다.

SMTP란? (Simple Mail Transfer Protocol)

전자 메일 전송을 위한 표준 프로토콜이다. 

이메일을 송수신하는 서버가 SMTP서버라고 한다.

 

nodemailer가 SMTP를 사용한다. 그리고 mailgun에서도 smtp를 사용할 수 있다고 한다.

 

 

 

https://next-auth.js.org/providers/email

 

Email | NextAuth.js

Overview

next-auth.js.org

nextauth 자체 기능을 사용해서 진행했다

signin 시에 provider에서 해당 email있는지 확인하는 로직으로 넘어간다

혼자서 따로 구현해봐야겠다...

728x90
728x90

핸드폰 개발자 모드로 설정!

usb 컴퓨터와 핸드폰 기기 연결 (c타입-c타입도 됨)

usb 테더링으로 설정

 

만약 다음과 같은 에러시 

 

Task :app:installDebug FAILED
error Failed to install the app. Make sure you have the Android development environment set up:

 

 

cd android

./gradlew clean

 

그리고!!!

 

깔려있는 앱삭제!

 

후 실행 

yarn android

 

 

 

https://velog.io/@rjc1704/React-Native-%EC%97%90%EB%9F%AC-%EB%8C%80%EC%9D%91

 

React Native 에러 로그 (Deprecated Gradle features)

npx react-native run-android 명령어로 앱 실행 시도 할 때 위와 같은 에러가 뜬다면, 아래 2가지 작업만 해주면 된다. 디렉터리 위치를 android 디렉터리 안으로 이동하여 ./gradlew clean 실행 에뮬레이터 또

velog.io

 

728x90
728x90

undefined 뜸~

graphql문제~

 

 

const Test1 = () => {

  const [tableNumber, setTableNumber] = useState('')


const CHECKTXID = gql`쿼리함수~~~`

const [
    FindTX,
    { loading: loadingCheckTxid, error: errorCheckTxid, data: dataCheckTxid },
  ] = useLazyQuery(CHECKTXID, {
    variables: {
      where: {
        //테이블번호
        id: Number(tableNumber),
      },
    },
  })



  console.log(tableNumber)
  return (
    <Layout title="Grid">
      <Row>
        <Col breakPoint={{ xs: 12 }}>
          <Card>
          
            <CardBody>
          
       
              <div>
                <Input fullWidth size="Small">
                  <input
                    type="text"
                    placeholder="tx테이블번호"
                    onChange={(e) => setTableNumber(e.target.value)}
              
                  />
               
                  <Button onClick={() => CheckTxid()}>출금txid요청</Button>
                </Input>
              </div>
            </CardBody>
          </Card>
        </Col>
      </Row>
    </Layout>
  )
}
export default Test1

쿼리 에러 뜬 이유!!!

 

input 

type을 text로 잡아놔서 string이 들어가는데

쿼리에도 string으로 id가 잡혀서 였음

 

type을 number로 바꾸거나 ->>>  안됨..

위처럼 id를 number로 감싸야한다.

728x90
728x90

Unhandled Runtime Error

Error: Objects are not valid as a React child (found: object with keys {findFirstTransaction}). If you meant to render a collection of children, use an array instead.

 

 

 

const check = () =>{

const { loading, error, data } = useQuery(CHECK_WITHDRAW, {
    variables: {
    
    },
  })


return (
<>{data}</>
)



}

data가 객체여서 뜨는 에러!!!

 

JSON.stringfy(data, undefined, 2)

 

하면 잘뜨는거 확인할 수 있음!

 

usequery는 렌더될 때 바로 실행돼서

버튼 할때만 하는 useLazyquery로 수정해야겠다...

둘의 차이는 자꾸 까먹으니까 정리해라 네네~

 

 

https://velog.io/@leehyunho2001/React-Query%EC%97%90%EC%84%9C-%EB%B2%84%ED%8A%BC-%ED%81%B4%EB%A6%AD%EC%8B%9C%EC%97%90-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A5%BC-%EC%9A%94%EC%B2%AD%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-feat.-useQuery

 

728x90
728x90

reactnative 설치 (xcode깔려있어야함.)

yarn ios 로 빌드 되는지 확인 !

 

 

빌드 fail경우 

cd ios

pod deintegrate (pods폴더 삭제)

pod cache clean --all (캐시 삭제)

(혹시 안되면 pod install --repo-update)

xcode preference에 들어가서 derived 폴더 안에 삭제. 

이거는 pod install 하면 다시 생김! 

(뭔말인지 모르겠으면 밑에 링크 참고)

 

yarn 

yarn ios

 

 

 

이제 

 

firebase project만들기

https://firebase.google.com/

 

Firebase

Firebase는 고품질 앱을 빠르게 개발하고 비즈니스를 성장시키는 데 도움이 되는 Google의 모바일 플랫폼입니다.

firebase.google.com

 

Add project

 

프로젝트 이름 넣고 

디폴트 내 계정으로 시작!

 

 

 

다음부터는 쭉 따라하면 되는데 

번들id는 xcode에서 가져와서 붙여넣기 하면 된다. 

(xcode에서 원하는 프로젝트파일 열고, 왼쪽의 프로젝트 파일 누르면 이거 뜸

General 들어가서 

Bundle Identifier 의 값을 복붙하면 됨다. )

 

 

 GoogleService-Info.plist 파일을 

firebase 프로젝트 만드는 곳에서 다운받아서

프로젝트 안에 넣는다 (위치는 거기서 알려줌.)

 

 

그다음에 

AppDelegate.m

에 

 

#import <Firebase.h>

와 

[FIRApp configure];

만 추가!

 

[FIRApp configure]; 이거는 (Bool)로 어플리케이션 실행하는 함수로 보이는 거 하단에 {} 넣어줌. 

위치는 마찬가지로 프로젝트 설명란에 있는데 각자 코드에 맞게 넣으면 된다..

 

 

특이점은 

appPackage를 다운받지 않았다. 

다음단계에서 링크로 들어가서 analytics다운 받는게 있는데 그걸 하지 않고

 

yarn add @react-native-firebase/app

yarn add @react-native-firebase/analytics

 

로 추가했다. (여기에 이미있다고함..)

 

 

아 그리고 analytics는 app과 같은 버전으로 맞춰줘야한다!

 

 

그리고 firebase.json파일을 보면

 

// <project-root>/firebase.json
{
  "react-native": {
    "analytics_auto_collection_enabled": false
  }
}

 

 

false로 꺼져있다.

잘은 모르겠지만 이게  GDPR compliance 정책상으로 꺼져있다고 한다.

앱실행될때 자동으로 집계하게끔 하는게 꺼져있는 것이다. 

대신 이벤트처리하듯

홈화면 들어갈 때 메서드를 이용해서 집계하는 방법을 쓰면 된다.

 

 

To re-enable analytics (e.g. once you have the users consent), call the setAnalyticsCollectionEnabled method:

import { firebase } from '@react-native-firebase/analytics';
// ...
await firebase.analytics().setAnalyticsCollectionEnabled(true);

https://rnfirebase.io/analytics/usage

 

Analytics | React Native Firebase

Copyright © 2017-2020 Invertase Limited. Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. Some partial documentation, under the

rnfirebase.io

 

 

프로젝트 예시 홈화면 들어갈때 추가되도록 했다. 

  const activateAnalytics = async () => {
    await firebase.analytics().setAnalyticsCollectionEnabled(true)
  }
  useEffect(() => {
    activateAnalytics()
  }, [])

 

 

 

 

 

 

 

 

 

 

에러 해결방법 참고한 것들

https://developer.apple.com/forums/thread/703823

 

Xcode 13.3 spits "Requested but di… | Apple Developer Forums

MrtnFbg's answer inspired me to read more about redirections of streams. So I read about Linux STDOUT STDERR. In this specific case when I run this command, there is an output and there are some errors. Since I ran this command on terminal and on terminal

developer.apple.com

https://positiveko-til.vercel.app/til/react-native/error65.html

 

에러 해결🔑 error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. | Positiveko

에러 해결🔑 error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. 리액트 네이티브에서 가장 유명한 에러가 아닐까.. (아니 나참.. 리네 = 에러 픽스 90 + 개발 10 같다.. 후) 이

positiveko-til.vercel.app

 

 

 

 

 

https://rnfirebase.io/analytics/usage

 

Analytics | React Native Firebase

Copyright © 2017-2020 Invertase Limited. Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. Some partial documentation, under the

rnfirebase.io

 

728x90
728x90

Can't use Watchman: "Operation not permitted"

 

Can't use Watchman: "Operation not permitted"

Since updating Watchman recently (with Homebrew) I can no longer use it to watch projects. I get { "version": "2022.05.30.00", "error": "std::__1::system_...

stackoverflow.com

watchman shutdown-server

로 해결

 

 

 

에러가 No bundle URL로 빨갛게 떴는데 

 

아래링크처럼

rm ios/build

로 삭제하고 

xcode에서 삭제해도 그대로 에러창 떴다. 

 

metro로 새로 뜨는 창에 

watchman 에러가 떠서 검색해보았다.

watchman 서버를 끄고 다시 실행하니까 잘 켜졌다. 

 

 

 

 

 

https://juzero-space.tistory.com/261

 

[React Native 에러 해결] IOS, No bundle URL present

1. 에러 상황 이유는 모르겠으나 No bundle URL present 에러가 발생했다. 아마 이것저것 만지다보니 나도 모르게 잘못 건드린거같다 ㅠ 2. 해결방법 해결방법이 간단하다. 다행.. 첫번째 방법) ios/build

juzero-space.tistory.com

 

 

728x90
728x90

미디어쿼리

max-width

최대여기 영역까지 css적용!

 

*그래서 순서도 큰 영역에서 작은 영역으로 써줘야 적용이 된다!!!!!!!

(이런느낌)

  @media screen and (max-width: 1440px) {
   
  }
  @media screen and (max-width: 1024px) {
   
  }

  @media screen and (max-width: 400px) {
   
  }

 

최소영역은 반대

작은 영역에서 큰영역으로 순서 써야함..

 

중앙정렬

중앙정렬할 때 

마진 오토가 안먹혀서 뭔가 했더니 가로값을 주어야했다!!

 position: fixed;
  /* fixed를 쓸 때에는 width, height를 명시해줘야 한다. */
  width: 460px
  /* left, right는 해당 요소의 위치 시작점을 결정한다. 그런데, 이때, margin의 양 값을 auto로 줌으로써 마진을 주어 해당 요소의 양 끝 위치를 각각 0으로 만들어준다. */
  margin: 0 auto;
  left: 0;
  right: 0;

출처 :https://wansook0316.github.io/dv/html-css/2020/03/19/position-fixed-center-%EC%A0%95%EB%A0%AC.html

 

////

position

postion: fixed

position:relative

position:absolute

....

https://developer.mozilla.org/ko/docs/Web/CSS/position

 

display:plex

 

 

 

728x90

'프론트 > Html Css' 카테고리의 다른 글

margin 값 방향  (0) 2021.10.26
box-sizing: border-box;  (0) 2021.10.26
box-shadow  (0) 2021.10.26
구조 가상 클래스 only-child /nth-of-type(n)  (0) 2021.08.23
:target :checked/ input type="checkbox"/필수입력창  (0) 2021.08.22
728x90

yarn build시 에러

 Build optimization failed: found page without a React Component as default export in
pages/types

 

error Command failed with exit code 1.

 

 

페이지마다 export default ,

default를 기본으로 하는애가 있어야한다고 이해해서 

페이지 types에 없어서 그런가 해봤는데 해결안됨

오히려 타입안에 인터페이스에 default붙이니까 못읽음

 

 

 

 

찾아보다가 

 

 

구성 요소를 페이지 폴더 외부로 이동해야 합니다. Pages/ Next.js 라우팅이 구조를 기반으로 하므로 페이지 구성 요소에만 사용해야 합니다 

Next.js에는 페이지 개념을 기반으로 구축된 파일 시스템 기반 라우터가 있습니다. 

파일이 페이지 디렉토리에 추가되면 자동으로 경로로 사용할 수 있습니다. 

위의 동작이 기본 동작이지만 페이지 디렉토리에 페이지가 아닌 파일을 포함하도록 Next.js 앱을 구성할 수 있습니다. 

이렇게 하려면 아래와 같이 next.config.js 파일의 pageExtensions 항목을 수정하면 됩니다. 그런 다음 .page(_document.page.js, _app.page.js, index.page.js )를 포함하는 파일 확장자를 갖도록 페이지 구성 요소의 이름을 바꿉니다.

 module.exports = {

    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']

}

이 구성을 사용하면 Next.js는 페이지/API 경로 및 라우팅을 구축하기 위해 .page를 포함하지 않는 모든 파일을 무시합니다.

 

 

 

이거보고 next.config.js에서 페이지별 설정 넣어야한다는 공식문서보고 혹시 넣어봤는데 build되네 호..

잘 모르겠음 그리고 빌드를 하면 out에 서버페이지가 생기는 거 맞나? 

dev는 개발모드고

정확한 차이를 정리해봐야겠다.

 

 

 

 

이 공식문서 봄

https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions#including-non-page-files-in-the-pages-directory

 

 

 

next.config.js

파일에 이거 추가함

module.exports = {
  pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}

 

 

다시 원위치..

 

 

문제는 이거를 넣으면 

기존 경로

local:3000 이 404로 페이지를 찾을 수 없다고 뜨고 안열린다. 

 

원래대로 지워줘야 뜨네 흠.. 

 

아 문서를 읽어보니 

pageExtensions를 넣고 나서 

이름을 바꿔줘야되는구나 

 

이름 바꿔줌

 

 

해결됨

 

라고 생각했는데 안떠서 다시..

 

https://stackoverflow.com/questions/65598753/cant-build-react-next-project-found-page-without-a-react-component-as-default

 

 

 

Can't build React/Next project - found page without a React Component as default export (context api file)

I'm trying to build my Next.js project but it keeps giving me this error in the terminal: Error: Build optimization failed: found page without a React Component as default export in pages/components/

stackoverflow.com

 

728x90
728x90

https://kyun2da.dev/react/%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%9D%BC%EC%9D%B4%ED%94%84%EC%82%AC%EC%9D%B4%ED%81%B4%EC%9D%98-%EC%9D%B4%ED%95%B4/

 

리액트 라이프사이클의 이해

시작하기 전에 리액트 라이프 사이클을 원래 알고는 있었지만 정확하게 한번도 정리해본 적이 없는 것 같아서 글을 쓰게 되었다. 더불어 리액트 라이프 사이클과 최근 사용되는 Hooks와도 비교해

kyun2da.dev

 

728x90
728x90

리액트 네이티브란?

페이스북에서 만든 오픈소스 모바일 애플리케이션 프레임워크이다.

 

HTML,CSS 대신 자바스크립트 스레드로 이뤄져 있다.

 

장점

 JavaScript를 사용하여 Android 와 iOS를  동시에 개발할 수 있어 효율적이다.

codePush를 통한 배포로 원하는 기능을 스토어를 거치지 않고 할 수 있다.

쉽고 빠른 UI 작성을 할 수 있다.

리액트 개발자가 사용하기 쉽다.

단점

성능이슈가 쉽게 나타나 낭비되는 렌더링을 확인해야 한다.

버그의 원인을 추적해나가는 과정이 다소 어렵다.

빌드타임이 오래 걸린다.

 

Windows, Linux 또는 Mac OS를 사용하여 React Native를 시작할 수 있습니다.

iOS 및 Android 환경은 Mac OS에서 모두 사용 가능하지만

Linux와 Windows는 Android 환경만 지원합니다.

React Native 개발을 위해 macOS를 사용한다고 하지만 Windows 및 Linux에서도

할 수 있다.

 

 

React Native 를 시작하는 두 가지 방법이 있다.

 

Expo CLI  

설치 및 배포가 쉬움 하지만 expo 라이브러리를 써야돼서 한정적일 수 있음

 

React Native CLI

설치해야되는 것들이 상대적으로 많음

 

 

 

 

expo란?

“create-react-native-app was replaced by expo-cli.”

Expo CLI는 개발자와 Expo 도구 간의 기본 인터페이스인 명령줄 앱입니다.

쉬운 앱개발을 할 수 있습니다.

Expo 는 ios, Android앱 개발할 수 있는 프레임워크이자 플랫폼이다

https://docs.expo.dev/workflow/expo-cli/

 

Expo CLI - Expo Documentation

Expo is an open-source platform for making universal native apps for Android, iOS, and the web with JavaScript and React.

docs.expo.dev

 

 

 

 

expo 설치 (with 타입스크립트)

 

Nodejs 가 설치되어있어야 한다.

 

npm install -g expo-cli

 

expo init 폴더명

cd 폴더명


npm start # you can also use: expo start

 

 

(expo 앱 깔아서 QR찍어서

핸드폰으로 연동해서 보면 되는데 

만약에 

android emulator로 보고 싶으면

 

Run on Android device/emulator 를 클릭하면, 자동으로 연결된다.

 

또는 터미널 상에서 a 버튼을 누르면 바로 실행된다.

Press a for Android emulator, or w to run on web.)

 

 

 

기존 프로젝트에 typescript 추가하기

npm install -D typescript @types/jest @types/react @types/react-native @types/react-test-renderer

 

참고 :

https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project

 

Using TypeScript · React Native

TypeScript is a language which extends JavaScript by adding type definitions, much like Flow. While React Native is built in Flow, it supports both TypeScript and Flow by default.

reactnative.dev

 

 

TypeScript 구성 파일을 추가합니다. tsconfig.json프로젝트의 루트에 생성

{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react-native",
"lib": ["es2017"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext"
},
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}

jest.config.jsTypeScript 사용하도록 Jest를 구성 하는 파일 만들기

module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

JavaScript 파일의 이름을 다음과 같이 변경하십시오.*.tsx

./index.js은 그대로 두어야 한다. 그렇지 않으면 프로덕션 빌드 번들링과 관련하여 문제가 발생할 수 있습니다.

 

yarn tsc

새 TypeScript 파일을 유형 검사하려면 실행하십시오 .

(만약 안된다면  npm install typescript –g 로 전역설치

https://stackoverflow.com/questions/39404922/tsc-command-not-found-in-compiling-typescript)

 

'tsc command not found' in compiling typescript

I want to install typescript, so I used the following command: npm install -g typescript and test tsc --version, but it just show 'tsc command not found'. I have tried many ways as suggested in

stackoverflow.com

 

 

 

 

 

 

 

 

 

react native cli 설치

 

 

1.자바 설치 (JDK)  Java Downloads | Oracle

- “고급 시스템 설정”에서 환경변수 수정 (시스템속성->환경변수 -> 새로 만들기)

변수 이름 적고, 하단에는 설치한 폴더 경로 입력 후 확인.

-시스템 변수에서 path 클릭, 새로 만들기 클릭, %JAVA_HOME%\bin 입력후 확인

-명령 프롬프트 에

 

javac    (javac 명령오는 텍스트 파일로 작성된 java 파일을 bytecode로 컴파일함)

java-version 입력해 버전 값 나오는지 확인

 

 

 

 

2. 안드로이드 스튜디오 설치 및 환경설정 Download Android Studio and SDK tools  |  Android Developers

-Tools에서 SDK manager 들어가서 사용할 디바이스 선택 및 설치

-환경변수 수정

 

 

 

3. Nodejs 설치 Node.js (nodejs.org)

4. Python 설치 Download Python | Python.org

5. npx react-native init AwesomeProject  

(타입스크립트 템플릿 추가

npx react-native init AwesomeTSProject --template react-native-template-typescript

)

6. npx react-native start

7. npx react-native run-android (새 터미널 창에서 입력, npm run android 해도 됨)

 

 

참고(특히 환경변수 설정 참고~~!) : https://marshmello.tistory.com/69

 

React Native 설치 및 프로젝트 생성하기

저번글에서는 리액트 네이티브가 무엇인지 작성하였습니다. https://marshmello.tistory.com/68?category=1213283 이번글에서는 리액트 네이티브로 프로젝트를 생성해 보도록 하겠습니다. 1. 자바 설치 및 환

marshmello.tistory.com

https://reactnative.dev/docs/environment-setup

 

에러났을 때

-에러 SDK tool 안 깔려 있는 것이 없는지 확인

-경로 확인(환경변수 확인)

 

에러 

error failed to launch emulator. Reason:No emulators found as an output of `emulator -list-avds` 

 

Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'. > SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file

해결

local.properties 파일 만들어서 해결

(sdk.dir=해당 경로 입력)

참고: https://healthcoding.tistory.com/35

https://eso0609.tistory.com/92 

https://stackoverflow.com/questions/59355688/how-to-solve-the-error-failed-to-launch-emulator-reason-no-emulators-found-as

 

How to solve the error, Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds` in React nat

I am creating react native app for mobile application. I am fully new in building react native app. I am using ubuntu for creating the app and following below link to create the app. https://facebook.

stackoverflow.com

 

 

 

728x90
728x90

scoop는 설치 프로그램

scoop로 설치한 프로그램은 scoop update *로 한번에 업데이트할 수 있음

 

 

파워셸에서 관리자 메뉴로 실행

Set-ExecutionPolicy RemoteSigned -scope CurrentUser

A-예 로 응답.

$env:SCOOP='C:\Scoop'

"환경변수 편집" 검색

새로 만들기 눌러서

변수이름 SCOOP

변수값 C:\Scoop

로 하고

 

다음명령어 실행했는데

 

계속 이 에러 떴음

Running the installer as administrator is disabled by default, see https://github.com/ScoopInstaller/Install#for-admin for details. 

 

(결국 환경변수 편집한거 삭제해봤는데 그게 문제는 아니었음. 하지만 다음 진행하다보니 삭제한 상태에서 깔아버린 나.. 사용자 안에 C:\안에 scoop가 생겼더라고)

 

해결)

관리자모드였던 창 끄고 새로운 power shell 창에서 실행했다

 

iex (new-object net.webclient).downloadstring('https://get.scoop.sh')

node 설치   (-> 이미 설치되어있어서 스킵)

LTS버전이 바람직하다고 함 리액트 네이티브 개발은 Nodejs버전에 영향을 받기 때문에!

에러 나면 나도 다시 깔아야지..

 

scoop install nodejs-lts
node -v

git 설치 -> 이미 설치되어있는데 무심코 깔아버린 나

scoop install git

 

자바8설치

리액트 네이티브 사용해서 안드로이드 앱만들려면 안드로이드 SDK빌드 도구가 필요하다. 근데 앱이 동작하는 안드로이드폰의 운영체제는 자바버전8이다. 자바버전8JDK 설치해야한다

scoop bucket add java

scoop install adopt8-hotspot

에러 뜸 ) Couldn't find manifest for 'adopt8-hotspot'.

자바버전 체크도 안됨

 

해결)

scoop install temurin8-jdk

버전 체크

java -version

 

 

비주얼 스튜디오도 깔려 있어서 넘어가고 

안깔려있따면 이거 하기

더보기

 (이제보니까 여기서 버킷을 하고 했으면 다음에 문제 없었겠구만!)

scoop bucket add extras
scoop install vscode

 

 

 

안드로이드 스튜디오와 개발도구인 안드로이드 SDK 설치할거야

scoop install android-studio android-sdk

에러) Couldn't find manifest for 'android-sdk'.

 

해결 )

scoop bucket add extras

 

다시 설치 실행

scoop install android-studio android-sdk

 

근데 스튜디오는 중간에 끊김..

다시 설치~

scoop install android-studio

 

 

휴~~

 

<에러에  도움 준 글>

https://www.pabburi.co.kr/content/javascript/%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EA%B8%B0%EB%B0%98-%EB%A6%AC%EC%95%A1%ED%8A%B8%EB%84%A4%EC%9D%B4%ED%8B%B0%EB%B8%8C-%EC%9C%88%EB%8F%84%EC%9A%B010-%EA%B0%9C%EB%B0%9C%ED%99%98%EA%B2%BD-%EC%84%A4%EC%A0%95/

 

728x90
728x90

노마드코더 강의 보는중

 

리액트 네이티브는 브라우저가 없음, 웹사이트가 아니야!

 

앱개발하는데 필요한 java 등등 깔아줄게 많음

 

그래서 강의에서는 네이티브 코드 바로 시작할 수 있게 expo 써서 한다.

핸드폰에 expo앱깔면 연동으로 보이네 신기하다

(expo 설치 내용 https://docs.expo.dev/)

 

( https://snack.expo.dev/ 여기서 작업하면 visual studio도 필요없고 node, npm 설치 안했어도 바로 테스트할 수 있음)

 

 

리액트 네이티브는 웹사이트가 아님!

HTML이 아니기 때문에 div쓸 수 없음

대신에 view를 씀 얘는 container컨테이너다 (react Native에서 import해와야 쓸 수 있음!)

(The most fundamental component for building UI, View is a container that supports layout with flexbox, style, some touch handling,,,)

 

react native에 있는 모든 텍스트는 text component안에 들어가야한다

border css는 사용불가능하다

 

처음에 react Native는 많은 컴포넌트와 API를 지원했는데 버그많고 비효율적이어서 

빠르게 만드는데 초첨맞추고 두 개를 축소시킴

 

(components와 API의 차이는 무엇인가?>

components는 화면에 렌더링할 항목이다

API는 (운영체제와 소통하는) 자바스크립트 코드이다)

 

reactNative 커뮤니티에서 쓸 수도 있지만

expo가 우리에게 필요한 Package를 제공한다.  https://docs.expo.dev/versions/v44.0.0/sdk/async-storage/

 

여기서는 이미 container View가 Flew container다

모바일에서는 Flex direction 기본값이 colum(열-세로)

(원래 웹에서는 Flex direction 기본값이 Row(행-가로) 였음)

 

레이아웃에서 대부분 width, height안씀. 반응형 페이지 생각해야함!!! 매번화면 달라지는데말여

React Native에서는 flex 비율로 레이아웃 채워서 씀

 

 

 

728x90
728x90

결론>

헤더와 푸터를 만들기 위해서 컴포넌트를 만들었는데

헤더랑 푸터 스크립트 안에 또 <Header/>로 컴포넌트 부르고 있어서 그랬다.

 

 

삽질>

캐시 지우고 

 

컴퓨터 고급 설정으로 메모리 더 사용하게 바꾸고

 

더 큰 메모리 할당하는 방법, 옵션 주는 것도 해봤는데 안됐다. 

 

728x90
728x90

따라하면서

순서, 필요한 내용 적기 

<이 순간, 최고의 강의_별점 백개 드립니다_>

https://www.youtube.com/watch?v=re3OIOr9dJI 

 

client -react 프론트

server -express, 백단

 

client/ npx create-react-app .

(.은 현재 위치를 의미함)

server/ npm init 

해서 package.json 생성하고

필요한 

mysql express 

설치

 

client/

Login.js

import { useState } from "react";
import "./login.css";

function Login() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState("");
  const [position, setPosition] = useState("");
  const [wage, setWage] = useState(0);

  const onChangefun = (event) => {
    setName(event.target.value);
    console.log(event.target.value);
  };
  return (
    <div className="login">
      <div className="information">
        <label>Name : </label>
        <input type="text" onChange={onChangefun}></input>
        <label>Age : </label>
        <input
          type="number"
          onChange={(event) => {
            setAge(event.target.value);
          }}
        ></input>
        <label>Country : </label>
        <input
          type="text"
          onChange={(event) => {
            setCountry(event.target.value);
          }}
        ></input>
        <label>Position : </label>
        <input
          type="text"
          onChange={(event) => {
            setPosition(event.target.value);
          }}
        ></input>
        <label>Wage: </label>
        <input
          type="number"
          onChange={(event) => {
            setWage(event.target.value);
          }}
        ></input>
        <button>직원 등록</button>
      </div>
    </div>
  );
}

export default Login;

 

server/

index.js

const express = require("express");
const app = express();

app.listen(3001, () => {
  console.log("your server is running on 3001~! yeah");
});

 

이제 mysql 설정해줄거임

 

mysql 워크벤치에서 

스키마 생성

테이블 생성

server/

디비저장 코드 입력

 

const express = require("express");
const app = express();
const mysql = require("mysql");

const db = mysql.createConnection({
  user: "root",
  host: "localhost",
  password: "비밀번호",
  database: "crudtest",
});

app.post("/create", (req, res) => {
  const name = req.body.frontname;
  const age = req.body.frontage;
  const country = req.body.frontcountry;
  const position = req.body.frontposition;
  const wage = req.body.frontwage;

  db.query(
    "INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?)",
    [name, age, country, position, wage],
    //콜백함수
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send("values Inserted");
      }
    }
  );
});

app.listen(3001, () => {
  console.log("your server is running on 3001~! yeah");
});

client/

import { useState } from "react";
import "./login.css";
import Axios from "axios";

function Login() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState("");
  const [position, setPosition] = useState("");
  const [wage, setWage] = useState(0);

  const addEmployee = () => {
    Axios.post("http://localhost:3001/create", {
      frontname: name,
      frontage: age,
      frontcountry: country,
      frontposition: position,
      frontwage: wage,
    }).then(() => {
      console.log("success");
    });
  };

  const onChangefun = (event) => {
    setName(event.target.value);
    console.log(event.target.value);
  };
  return (
    <div className="login">
      <div className="information">
        <label>Name : </label>
        <input type="text" onChange={onChangefun}></input>
        <label>Age : </label>
        <input
          type="number"
          onChange={(event) => {
            setAge(event.target.value);
          }}
        ></input>
        <label>Country : </label>
        <input
          type="text"
          onChange={(event) => {
            setCountry(event.target.value);
          }}
        ></input>
        <label>Position : </label>
        <input
          type="text"
          onChange={(event) => {
            setPosition(event.target.value);
          }}
        ></input>
        <label>Wage: </label>
        <input
          type="number"
          onChange={(event) => {
            setWage(event.target.value);
          }}
        ></input>
        <button onClick={addEmployee}>직원 등록</button>
      </div>
    </div>
  );
}

export default Login;

프런트에서 백 전달할때 

우리는 api허용해주기 위해서 cors 라이브러리 사용할거임

npm i cors

 

server/ index.js 파일에

const cors = require("cors");
app.use(cors());

추가

 

 

 

 

근데 여전히 막상보면 백으로 못넘어옴

이렇게 req.body 콘솔 찍어보면 

undefined 뜸 

 

json 미들웨어를 제공안해서였음

프런트에서 보낼때 

 

 

index.js/

app.use(express.json());

이거 추가

 

유튜브영상에서는 이거 추가하면 db넣기 성공했는데 난 안됨. ㅎ

 

 db에 안들어가고 

에러 뜸

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

 

 

이거 mysql에 외부접근안돼서 그런거라고 함  

그래서 이걸로 해결가능하다고 함( 비번 사용해서 db계정사용하게끔 하는 설정인듯!)

 

+해결방법중에 mysql2쓰는 것도 있음 이번에는 안해봄 

 ALTER user '[유저]'@'localhost' IDENTIFIED WITH mysql_native_password by '[비번]';

 바꿔주기 위해서 mysql로 ㄱㄱ

mysql에 바로 use mysql하면 접속이 안됨

mysql -u root -p도 당연히 안됨

 

 

'use'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다

워크벤치 경로로 들어가서 해야함~~~

C:\Program Files\MySQL\MySQL Server 8.0\bin

 

 

cd C:\Program Files\MySQL\MySQL Server 8.0\bin

mysql -u root -p

 

이제 mysql켜짐

 

mysql>

 

 

계정 뭐있는지 확인 먼저 함

 

SELECT user,authentication_string,plugin,host FROM mysql.user;

 

내가 쓸 root계정 있는거 확인함

 

 

 

 

 ALTER user '[유저]'@'localhost' IDENTIFIED WITH mysql_native_password by '[비번]';

 

flush privileges;

 

 

 

index.js 

서버 끄고 다시 실행

node index.js

로 실행

 

 

직원등록 눌러서 보내보면 

 

잘 들어왔다~!~!~!~!~!

 

 

 

이제 우리가 할거는

백-> 프런트로 

정보 가져오는걸 할거임

우리는 필요할 때 정보를 봐야하니까 

 

 

client/

//초기에는 빈배열이니까 []로 넣어줌 
 const [employeesList, setEmployeesList] = useState([]);
 //가져올 함수// 백가져온 응답반은걸 콘솔로 보여주겠음 response가져온거의 data로
   const getEmployee = () => {
    Axios.get("http://localhost:3001/employees").then((response) => {
      setEmployeesList(response.data);
    });
  };
  
  
 //버튼
   <div className="showDB">
      //버튼눌렀을 때 가져올 함수 실행
        <button className="showDB-button" onClick={getEmployee}>
          show employees
        </button>
      </div>

 

server/

app.get("/employees", (req, res) => {
//db에서 employess테이블 다 가져와
  db.query("SELECT * FROM employees", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

버튼 누르면

이건 response임 

object 객체로 가져옴

(status 200 -> 작동한거임)

이안에 우리가 원하는 정보가 잘 담겨져있음

 

 

이제 백에서 가져온 것들을 화면에 띄워줄거임

맵함수 사용해서

배열에서 하나씩 꺼내오기 

 

        <div>
          {employeesList.map((val, index) => {
            return (
              <div className="employee">
                <h3>{val.name}</h3>
                <h3>{val.age}</h3>
                <h3>{val.country}</h3>
                <h3>{val.position}</h3>
                <h3>{val.wage}</h3>
              </div>
            );
          })}
        </div>

성공~~~

 

 

근데 다른 방법도 있대 

post에 넣고 바로 화면에 띄우게 하는법

 

const addEmployee = () => {
    console.log(name, "dfdfd");
    Axios.post("http://localhost:3001/create", {
      frontname: name,
      frontage: age,
      frontcountry: country,
      frontposition: position,
      frontwage: wage,
    }).then(
      //   () => {
      //   console.log("success");
      // }
      () => {
        //기존 배열에 방금 입력한 걸 추가하고 그걸 setEmployessList함수에 넣음! 배경은 뜨는데 값이 안띄워지네..흠
        //암튼 여러 방법이 있다고 함 있다가 해보자
        setEmployeesList([
          ...employeesList,
          {
            frontname: name,
            frontage: age,
            frontcountry: country,
            frontposition: position,
            frontwage: wage,
          },
        ]);
      }
    );
  };

나는 왜인지 빈값만 뜸

 

db에는 잘들어갔는데...

왜 안뜨는 것인가...

이부분은 다른 날에 해보겟음

 

 

이제 

삭제 하고 수정하고 다음에 해봐야지

db에서 가져온 목록 선택해서 나열하게 하고

이런 것도 해보고 싶네 

 

아 그리고 지금은 새로고침하면 db에서 블러온 애들이 화면에서 사라지거든

그것도 막아야겠다.

728x90
728x90

state변경할 때 모든 code들은 항상 다시 실행됨

근데 api가져와서 쓸때를 예를 들면 매번 다시 가져오면 번거로워지지

 

몇몇 코드를 처음에 딱 한번만 실행되고 다시 실행안되게 하고 싶음

 

useEffect(우리가 실행시킬함수,[변경되는지 지켜볼애])

 

 

 

 

처음 렌더링됐을 때 한번만 실행되고

버튼 눌러서 state바뀔 때 실행되지 않음

 


+코드제어

 

클릭할때 keyword 검색코드 다시 실행안되게 막기

키워드를 검색할 때만 실행되게 하기

[keyword]로 넣어서 이 keyword  state값이 변경될때만 이 코드 실행됨

조건으로 keyword가 비어있고 keyword길이가 5이상일때만 실행되게 하였음

 

 

 

처음에는 실행안됐고

검색창에 6자넣으니까 실행됨 

 

 

 

---

[] 아무것도 지켜보지 않거나

[keyword] 키워드 변경하는지 보거나

[keyword, counter] 둘다 변경하는지 보거나 (둘중 하나 변경될때 실행)

이렇게 쓸 수 있음

728x90
728x90
npm i prop-types

728x90
728x90

server.js에서 db확인할게 있어서

 

npm start했는데

  

UnhandledPromiseRejectionWarning: Error: Could not find a production build in the 

이 에러 뜸

 

그래서 

npm run build

했는데 에러

 

 

 

 throw er; // Unhandled 'error' event
      ^

Error: EPERM: operation not permitted, open 경로
Emitted 'error' event on WriteStream instance at:

 

해결: 실행해놓은 npm run dev 취소하고 하니까 됨

이거 하기 전에 build해야되는거임

 

 

 

빌드 잘됨

728x90

+ Recent posts