
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
여전히 오류가 발생합니다. 뭔가 또 코드를 잘못 작성한 듯합니다;;
.png)
작성한 코드 및 에러 메세지
앞글에 추가 질문으로 올렸는데 못 보시는 듯해서 새 글로 질문드려요;;
import React from 'react';
//설치한 스택 네비게이션 라이브러리를 가져옵니다
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import { Text, StyleSheet, StackNavigator, StackScreen } from 'react-native';
//페이지로 만든 컴포넌트들을 불러옵니다
import DetailPage from '../pages/DetailPage';
import MainPage from '../pages/MainPage';
import AboutPage from '../pages/AboutPage';
import LikePage from '../pages/LikePage';
//스택 네비게이션 라이브러리가 제공해주는 여러 기능이 담겨있는 객체를 사용합니다
//그래서 이렇게 항상 상단에 선언하고 시작하는게 규칙입니다!
const Stack = createStackNavigator();
const StackNavigator = () =>{
return (
//컴포넌트들을 페이지처럼 여기게끔 해주는 기능을 하는 네비게이터 태그를 선언합니다.
//위에서 선언한 const Stack = createStackNavigator(); Stack 변수에 들어있는 태그를 꺼내 사용합니다.
//Stack.Navigator 태그 내부엔 페이지(화면)를 스타일링 할 수 있는 다양한 옵션들이 담겨 있습니다.
<NavigationContainer>
<StackNavigator
screenOptions={{
headerStyle: {
backgroundColor: "white",
borderBottomColor: "white",
shadowColor: "white",
height:100
},
//헤더의 텍스트를 왼쪽에 둘지 가운데에 둘지를 결정
headerTitleAlign:'left',
headerTintColor: "#000",
headerBackTitleVisible: false
}}
>
<Text style={{ fontFamily: 'An', fontSize: 30 }}>An</Text>
<Text style={{ fontFamily: 'An-Bold', fontSize: 30, fontFamily: 'An-ESG', fontSize: 20 }}>An-Bold, An-ESG</Text>
<StackScreen name="MainPage" component={MainPage}/>
<StackScreen name="DetailPage" component={DetailPage}/>
<StackScreen name="AboutPage" component={AboutPage}/>
<StackScreen name="LikePage" component={LikePage}/>
</StackNavigator>
</NavigationContainer>
);
};
const styles = StyleSheet.create({
headerTitle: {
fontFamily: 'An-Bold',
fontSize: 30,
color: 'black',
},
headerSubtitle: {
fontFamily: 'An-ESG',
fontSize: 20,
color: 'black',
},
});
export default StackNavigator;
StackNavigator 에 적용한 코드입니다.
.png)
17 |
18 |
> 19 | const StackNavigator = () =>{
| ^
20 | return (
21 |
22 | //컴포넌트들을 페이지처럼 여기게끔 해주는 기능을 하는 네비게이터 태그를 선언합니다.
Android Bundling failed 17ms
SyntaxError: C:\Users\USER\Desktop\sparta-study\spart-name-khj\navigation\StackNavigator.js: Identifier 'StackNavigator' has already been declared. (19:6)
17 |
18 |
> 19 | const StackNavigator = () =>{
| ^
20 | return (
21 |
| ^
| ^
20 | return (
21 | 22 | //컴포넌트들을 페이지처럼 여기게끔 해주는 기능을 하는 네비게이터 태그를 선언합니다.
지금 뜨는 에러입니다;;
메인페이지는
import React,{useState,useEffect} from 'react';
import { StyleSheet, Text, ClassText, View, Image, TouchableOpacity, SafeAreaView, ScrollView} from 'react-native';
import data from '../data.json';
import Card from '../components/Card';
import Loading from '../components/Loading';
import { StatusBar } from 'expo-status-bar';
import * as Location from "expo-location";
import axios from "axios"
import {firebase_db} from "../firebaseConfig"
import { BannerAd, BannerAdSize, TestIds } from 'react-native-google-mobile-ads';
const adUnitId = __DEV__ ? TestIds.BANNER : 'ca-app-pub-8534463316422476/4889143218';
export default function MainPage({navigation,route}) {
//useState 사용법
//[state,setState] 에서 state는 이 컴포넌트에서 관리될 상태 데이터를 담고 있는 변수
//setState는 state를 변경시킬때 사용해야하는 함수
//모두 다 useState가 선물해줌
//useState()안에 전달되는 값은 state 초기값
const [state,setState] = useState([])
const [cateState,setCateState] = useState([])
//날씨 데이터 상태관리 상태 생성!
const [weather, setWeather] = useState({
temp : 0,
condition : ''
})
//하단의 return 문이 실행되어 화면이 그려진다음 실행되는 useEffect 함수
//내부에서 data.json으로 부터 가져온 데이터를 state 상태에 담고 있음
const [ready,setReady] = useState(true)
useEffect(()=>{
navigation.setOptions({
title:'나를 빛나게 할 명언'
})
//뒤의 1000 숫자는 1초를 뜻함
//1초 뒤에 실행되는 코드들이 담겨 있는 함수
setTimeout(()=>{
firebase_db.ref('/tip').once('value').then((snapshot) => {
console.log("파이어베이스에서 데이터 가져왔습니다!!")
let tip = snapshot.val();
setState(tip)
setCateState(tip)
getLocation()
setReady(false)
});
// getLocation()
// setState(data.tip)
// setCateState(data.tip)
// setReady(false)
},1000)
},[])
const getLocation = async () => {
//수많은 로직중에 에러가 발생하면
//해당 에러를 포착하여 로직을 멈추고,에러를 해결하기 위한 catch 영역 로직이 실행
try {
//자바스크립트 함수의 실행순서를 고정하기 위해 쓰는 async,await
await Location.requestForegroundPermissionsAsync();
const locationData= await Location.getCurrentPositionAsync();
console.log(locationData)
console.log(locationData['coords']['latitude'])
console.log(locationData['coords']['longitude'])
const latitude = locationData['coords']['latitude']
const longitude = locationData['coords']['longitude']
const API_KEY = "cfc258c75e1da2149c33daffd07a911d";
const result = await axios.get(
`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
);
console.log(result)
const temp = result.data.main.temp;
const condition = result.data.weather[0].main
console.log(temp)
console.log(condition)
//오랜만에 복습해보는 객체 리터럴 방식으로 딕셔너리 구성하기!!
//잘 기억이 안난다면 1주차 강의 6-5를 다시 복습해보세요!
setWeather({
temp,condition
})
} catch (error) {
//혹시나 위치를 못가져올 경우를 대비해서, 안내를 준비합니다
Alert.alert("위치를 찾을 수가 없습니다.", "앱을 껐다 켜볼까요?");
}
}
const category = (cate) => {
if(cate == "전체보기"){
//전체보기면 원래 꿀팁 데이터를 담고 있는 상태값으로 다시 초기화
setCateState(state)
}else{
setCateState(state.filter((d)=>{
return d.category == cate
}))
}
}
//data.json 데이터는 state에 담기므로 상태에서 꺼내옴
// let tip = state.tip;
let todayWeather = 10 + 17;
let todayCondition = "흐림"
//return 구문 밖에서는 슬래시 두개 방식으로 주석
return ready ? <Loading/> : (
/*
return 구문 안에서는 {슬래시 + * 방식으로 주석
*/
<View>
{__DEV__ ? null : (<BannerAd
unitId={adUnitId}
size={BannerAdSize.FULL_BANNER}
requestOptions={{
requestNonPersonalizedAdsOnly: true,
}}
/>)}
<SafeAreaView style={styles.container}>
<ScrollView style={styles.container}>
<StatusBar style="dark" />
{/* <Text style={styles.title}>나를 빛나게 할 명언 모음</Text> */}
<Text style={styles.weather}>오늘의 날씨: {weather.temp + '°C ' + weather.condition} </Text>
<TouchableOpacity style={styles.aboutButton} onPress={()=>{navigation.navigate('AboutPage')}}>
<Text style={styles.aboutButtonText}>가열차게 달려온 나에게</Text>
</TouchableOpacity>
<Image style={styles.mainImage} source={{uri:main}}/>
<ScrollView style={styles.middleContainer} horizontal indicatorStyle={"green"}>
<TouchableOpacity style={styles.middleButtonAll} onPress={()=>{category('전체보기')}}><Text style={styles.middleButtonTextAll}>전체보기</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton01} onPress={()=>{category('성장')}}><Text style={styles.middleButtonText}>성장</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton02} onPress={()=>{category('사랑')}}><Text style={styles.middleButtonText}>사랑</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton03} onPress={()=>{category('인생')}}><Text style={styles.middleButtonText}>인생</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton04} onPress={()=>{category('감사')}}><Text style={styles.middleButtonText}>감사</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton05} onPress={()=>{category('지혜')}}><Text style={styles.middleButtonText}>지혜</Text></TouchableOpacity>
<TouchableOpacity style={styles.middleButton06} onPress={()=>{navigation.navigate('LikePage')}}><Text style={styles.middleButtonText}>저장</Text></TouchableOpacity>
</ScrollView>
<View style={styles.cardContainer}>
{/* 하나의 카드 영역을 나타내는 View */}
{
cateState.map((content,i)=>{
return (<Card content={content} key={i} navigation={navigation}/>)
})
}
</View>
</ScrollView>
</SafeAreaView>
</View>
)
}
const styles = StyleSheet.create({
headerTitle: {
fontFamily: 'An-Bold',
fontSize: 30,
color: 'black',
},
headerSubtitle: {
fontFamily: 'An-ESG',
fontSize: 20,
color: 'black',
},
container: {
//앱의 배경 색
backgroundColor: '#fff',
},
title: {
//폰트 사이즈
Size: 20,
//폰트 두께
Weight: '700',
//위 공간으로 부터 이격
marginTop:30,
//왼쪽 공간으로 부터 이격
marginLeft:20
},
weather:{
alignSelf:"flex-end",
paddingRight:20
},
mainImage: {
//컨텐츠의 넓이 값
width:'90%',
//컨텐츠의 높이 값
height:250,
//컨텐츠의 모서리 구부리기
borderRadius:10,
marginTop:20,
//컨텐츠 자체가 앱에서 어떤 곳에 위치시킬지 결정(정렬기능)
//각 속성의 값들은 공식문서에 고대로~ 나와 있음
alignSelf:"center"
},
middleContainer:{
marginTop:15,
marginLeft:15,
height:60
},
middleButton01: {
width:100,
height:50,
padding:15,
backgroundColor:"#3edcf7",
borderColor:"darkblue",
borderRadius:15,
margin:5
},
middleButton02: {
width:100,
height:50,
padding:15,
backgroundColor:"#ff99ff",
borderRadius:15,
margin:5
},
middleButton03: {
width:100,
height:50,
padding:15,
backgroundColor:"#00d832",
borderRadius:15,
margin:5
},
middleButton04: {
width:100,
height:50,
padding:15,
backgroundColor:"#ae80ff",
borderRadius:15,
margin:5
},
middleButton05: {
width:100,
height:50,
padding:15,
backgroundColor:"#fe8d6f",
borderRadius:15,
margin:5
},
middleButton06: {
width:100,
height:50,
padding:15,
backgroundColor:"purple",
borderRadius:15,
margin:5
},
middleButtonAll: {
width:100,
height:50,
padding:15,
backgroundColor:"#006633",
borderColor:"deeppink",
borderRadius:15,
margin:5
},
middleButtonText: {
color:"#fff",
Weight:"700",
//텍스트의 현재 위치에서의 정렬
textAlign:"center"
},
middleButtonTextAll: {
color:"#fff",
Weight:"700",
//텍스트의 현재 위치에서의 정렬
textAlign:"center"
},
cardContainer: {
marginTop:15,
marginLeft:10
},
aboutButton: {
backgroundColor:"blue",
width:170,
height:40,
borderRadius:10,
alignSelf:"flex-end",
marginRight:20,
marginTop:10
},
aboutButtonText: {
color:"#fff",
textAlign:"center",
marginTop:10
}
});
이렇게 적용한 상태이구요;;
개발하시는 분들 돈 많이 줘야 할 듯한.. 느낌이;;
어렵네요.
시작했으니 중도 포기도 못하고..
무튼 믿는 빽이 있으니 막 저지르고 있습니다..
*스택네비게이터와 메인페이지 폰트 적용을 위해 코드를 바꿨는데
폰트적용은 안 되고 또 오류가.. 뜨네요;;
음.. 넘 죄송한 느낌이..;;
그래두 꼭 폰트 적용해서 앱 올려보고 싶어요.
감사합니다.
