我收到此错误"类型错误:null 不是对象(评估'son['business']')" 我不确定问题是什么,因为当我写"儿子['企业'][1]['名称']"时,我只从"儿子"开始,当我添加"['企业'][1]['名称']"时,没有抛出任何错误。但是当我重新启动模拟器时,它现在抛出了一个错误。
const [son, setSon] = useState(null);
fetch("https://api.yelp.com/v3/businesses/search?term=burger&location=90706&limit=2", requestOptions)
.then(response => response.json())
.then(result => db.collection("group")
.doc(roomCode)
.set(result))
.catch(error => console.log('error', error));
const fetchData = async () => {
try {
await db
.collection('group')
.doc(route.params.roomCode)
.get()
.then((documentSnapshot) => {
if (documentSnapshot.exists) {
setSon(documentSnapshot.data());
} else {
console.log('hello');
}
})
} catch (err) {
Alert.alert('There is something wrong!', err.message);
}
}
useEffect(() => {
console.log('completed');
fetchData();
console.log('son', son['businesses'][1]['name']);
}, []);
import React, {useRef} from "react";
import { useEffect, useState } from 'react';
import { useNavigation } from '@react-navigation/core';
//import { NavigationContainer } from '@react-navigation/native';
//import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { StyleSheet, Text, TouchableOpacity, Alert, View, Image, FlatList, SafeAreaView} from "react-native";
import styles from "./styles";
import { doc, setDoc, getDoc, onSnapshot } from "firebase/firestore";
import { db, auth } from "../../firestore";
import firebase from "firebase";
import Icon from 'react-native-vector-icons/FontAwesome';
import IconMaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import Swiper from "react-native-deck-swiper";
import {BEARER_TOKEN} from '../hooks/yelp-api/config';
const DUMMY_DATA = [
{
restaurantName: 'Marufuku Ramen',
occupation: "bricks",
photoURL: "https://s3-media0.fl.yelpcdn.com/bphoto/ouK2VmW0SrI70jsJpTxJhw/1000s.jpg",
age: 27,
id: 123,
},
{
restaurantName: 'Farmhouse Kitchen Thai Cuisine',
occupation: "nothing",
photoURL: "https://s3-media0.fl.yelpcdn.com/bphoto/kUlEaPpv0JGlHG_nrPr7wQ/1000s.jpg",
age: 23,
id: 124,
},
{
restaurantName: 'Sotto Mare Oysteria & Seafood',
occupation: "everything",
photoURL: "https://s3-media0.fl.yelpcdn.com/bphoto/o3hIcGLMxV_5ynxEjGWGrw/1000s.jpg",
age: 99,
id: 125,
}
]
const GroupSwipe = ({navigation, route, roomZipCode}) => {
const roomCode = route.params.roomCode;
const swipeRef = useRef(null);
const [son, setSon] = useState({});
//const [result, setresult] = useState()
console.log('roomZipCode',roomZipCode);
useEffect(() =>{
var myHeaders = new Headers();
myHeaders.append("Authorization", BEARER_TOKEN);
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://api.yelp.com/v3/businesses/search?term=burger&location=90706&limit=2", requestOptions)
.then(response => response.json())
.then(result => db.collection("group")
.doc(roomCode)
.set(result))
.catch(error => console.log('error', error));
})
const fetchData = async () => {
try {
await db
.collection('group')
.doc(route.params.roomCode)
.get()
.then((documentSnapshot) => {
if (documentSnapshot.exists) {
setSon(documentSnapshot.data());
} else {
console.log('hello');
}
})
} catch (err) {
Alert.alert('There is something wrong!', err.message);
}
}
useEffect(() => {
console.log("completed");
fetchData().then((data) => {
setSon(data);
console.log("son", son["businesses"][1]["name"]);
})
}, []);
// useEffect(() => {
// console.log('completed');
// fetchData();
// console.log('son', son['businesses'][1]['name']);
// }, []);
return (
<SafeAreaView style={styles.safe}>
<View style={styles.buttonContainerHome}>
<TouchableOpacity
onPress={() => navigation.navigate('GroupStart') }
style={styles.buttonHome}
>
<Text style={styles.buttonTextHome}>FOOD FIGHT</Text>
</TouchableOpacity>
</View>
<View style={styles.roomId}>
<Text style ={styles.roomIdText}>Room ID: {roomCode}</Text>
</View>
{/* <View style={styles.resturantName}>
<Text style ={styles.resturantNameText}>Chick Fil A</Text>
</View> */}
<View style={styles.cards}>
<Swiper
ref={swipeRef}
containerStyle={{backgroundColor: 'transparent'}}
cards={DUMMY_DATA}
stackSize={3}
cardIndex={0}
animateCardOpacity
verticalSwipe={false}
renderCard={(card) => (
<View style={styles.cardstyle}
key={card.id} >
{/* style={tw("relative bg-white h-3/4 rounded-xl")}> */}
<Text style={{alignSelf: 'center', margin:10, fontSize: 18, fontWeight: 'bold',}}>{card.restaurantName}</Text>
<Image
style={{ alignSelf: 'center', width: 300,
height: 300,resizeMode: 'contain', borderRadius: 5,
margin:15, borderRadius: 20, justifyContent: 'center'}}
source={{ uri: card.photoURL }}
/>
</View>
)}
/>
</View>
<View style = {styles.functionList}>
<TouchableOpacity onPress={() => {}} style = {styles.functionButton}>
<Icon name="undo" size={50} color="#ECD55D" />
</TouchableOpacity>
<TouchableOpacity onPress={() => swipeRef.current.swipeLeft()} style = {styles.functionButton}>
<Icon name="times-circle-o" size={80} color="#AA4747" />
</TouchableOpacity>
<TouchableOpacity onPress={() => swipeRef.current.swipeRight()} style = {styles.functionButton}>
<Icon name="check-circle-o" size={80} color="#9DC151" />
</TouchableOpacity>
<TouchableOpacity onPress={() => {}} style = {styles.functionButton}>
<IconMaterialCommunityIcons name="star-circle-outline" size={55} color="#75B9DF" />
</TouchableOpacity>
</View>
</SafeAreaView>
)
}
export default GroupSwipe
[未处理的承诺拒绝:类型错误:未定义不是一个对象(评估'儿子["业务"][1])] at node_modules/@firebase/storage/dist/index.browser.esm.js:3561:30 in UploadTaskCompat.prototype.on
我尝试使用异步函数并等待 fetchData(),但它没有解决问题。
useEffect
组件挂载、更新(如果有依赖项)和卸载(如果有返回方法)时运行。
这里发生的事情是,当组件挂载时,它会触发useEffect
并发生以下情况:
console.log('completed')
立即运行- 然后第二行执行
fetchData()
这是一个异步调用,因为你在这里没有等待它,所以第三行执行console.log('son', son['businesses'][1]['name']);
,此时,fetchData
仍在尝试从 API 获取数据,因此第三行失败,因为son
仍然为 null。
最简单的解决方案是执行以下操作:
useEffect(() => {
console.log("completed");
fetchData().then((data) => {
setSon(data);
console.log("son", son["businesses"][1]["name"]);
})
}, []);