使用搜索栏从 API 获取数据
Get data from API with Search Bar
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
searchValue: "",
};
}
updateSearch = (value) => {
this.setState({ searchValue: value });
if (value.trim() !== "") {
axios
.get(
`https://api.spoonacular.com/food/products/search?apiKey=1234&query=${value}&number=100`
)
.then((res) => {
this.setState({ data: res.data });
})
.catch((error) => {
console.log(error.response.data);
});
} else {
setState({ data: [] });
}
}}
render() {
const {
data,
searchValue,
} = this.state;
return (
<SearchBar
placeholder="Search Food..."
onChangeText={this.updateSearch}
value={searchValue}
<List style={{ paddingTop: hp("2%") }}>
<TouchableOpacity>
{this.state.data.map(({ type }) => (
<Text>{this.state.type.products.title}</Text>
))}
</TouchableOpacity>
</List>
嗨,我正在尝试使用 SearchBar
和 axios
从 Spoonacular API 获取数据,当我 运行 代码时出现以下错误: undefined is not a function (near '...this.state.data.map...')
Link 到数据库的文档:https://spoonacular.com/food-api/docs#Search-Grocery-Products
我认为您的问题是您正在尝试使用 。
用 FlatList
替换您的地图
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<Text>{item.products.title}</Text>
))}
keyExtractor={item => item.id}
/>
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
searchValue: "",
};
}
updateSearch = (value) => {
this.setState({ searchValue: value });
if (value.trim() !== "") {
axios
.get(
`https://api.spoonacular.com/food/products/search?apiKey=1234&query=${value}&number=100`
)
.then((res) => {
this.setState({ data: res.data });
})
.catch((error) => {
console.log(error.response.data);
});
} else {
setState({ data: [] });
}
}}
render() {
const {
data,
searchValue,
} = this.state;
return (
<SearchBar
placeholder="Search Food..."
onChangeText={this.updateSearch}
value={searchValue}
<List style={{ paddingTop: hp("2%") }}>
<TouchableOpacity>
{this.state.data.map(({ type }) => (
<Text>{this.state.type.products.title}</Text>
))}
</TouchableOpacity>
</List>
嗨,我正在尝试使用 SearchBar
和 axios
从 Spoonacular API 获取数据,当我 运行 代码时出现以下错误: undefined is not a function (near '...this.state.data.map...')
Link 到数据库的文档:https://spoonacular.com/food-api/docs#Search-Grocery-Products
我认为您的问题是您正在尝试使用
用 FlatList
替换您的地图<FlatList
data={this.state.data}
renderItem={({ item }) => (
<Text>{item.products.title}</Text>
))}
keyExtractor={item => item.id}
/>