我正在尝试构建一个基本的应用程序,我可以从yelp api获取一些餐馆。
我在iOS上收到以下错误,但我似乎无法修复它。
对象作为 React 子对象无效(找到:带有键 {id, 别名、名称、image_url、is_closed、网址、review_count、类别、 评级, 坐标, 交易, 价格, 位置, 电话, display_phone,距离}(。如果您打算呈现 孩子,请改用数组。
当我从<ResultsList>
中删除部分results={filterResultsByPrice('$')}
时,该应用程序再次运行。
如果有人能帮忙,将不胜感激。
这是我的主屏幕:
import React, {useState} from 'react';
import { View, Text, StyleSheet } from 'react-native';
import SearchBar from '../component/SearchBar';
import useResults from '../hooks/useResults';
import ResultsList from '../component/ResultsList';
const SearchScreen = () => {
const [term, setTerm] = useState('');
const [searchApi, results, errorMessage] = useResults();
const filterResultsByPrice = (price) => {
return results.filter( result => {
return result.price === price;
});
};
return (
<View>
<SearchBar
term={term}
onTermChange={(newTerm)=> setTerm(newTerm)}
onTermSubmit={searchApi}
/>
{errorMessage ? <Text>{errorMessage}</Text> : null }
<Text>We have found {results.length} results</Text>
<ResultsList results={filterResultsByPrice('$')} title="Cost Effective"/>
<ResultsList results={filterResultsByPrice('$$')} title="Bit Pricier"/>
<ResultsList results={filterResultsByPrice('$$$')} title="Big Spender"/>
</View>
);
};
const styles = StyleSheet.create({});
export default SearchScreen;
这是我想放在屏幕上的组件:
import React from 'react';
import { View, Text, StyleSheet} from 'react-native';
const ResultsList = ({ title, results }) => {
return (
<View>
<Text style={styles.title}> {title}</Text>
<Text> Results: {results.length} </Text>
</View>
);
};
const styles = StyleSheet.create({
title:
{
fontSize: 18,
fontWeight: 'bold'
}
});
export default ResultsList;
这是我的用途结果钩子:
import {useEffect, useState } from 'react';
import yelp from '../api/yelp';
export default () => {
const [results, setResults] = useState([]); //default is empty array
const [errorMessage, setErrorMessage] = useState('');
const searchApi = async searchTerm=> {
console.log('Hi there');
try {
const response = await yelp.get('/search', {
params: {
limit: 50,
term: searchTerm,
location: 'san jose'
}
});
setResults(response.data.businesses);
} catch (err) {
setErrorMessage('Something went wrong.');
}
};
useEffect(()=> {
searchApi('pasta');
}, []);
return [searchApi, results, errorMessage];
};
您需要将 ResultsList 组件更新为此组件,希望它能永久解决您的问题:
import React from "react";
import { View, Text, StyleSheet } from "react-native";
const ResultsList = ({ title, results }) => {
return (
<View>
<Text style={styles.title}> {title}</Text>
{results.map(result => (
<Text>Results: {result.length}</Text>
))}
</View>
);
};
const styles = StyleSheet.create({
title: {
fontSize: 18,
fontWeight: "bold"
}
});
export default ResultsList;