【发布时间】:2021-03-26 02:01:03
【问题描述】:
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}
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<Text>{item.products.title}</Text>
)}
keyExtractor={item => item.id}
/>
大家好,我正在尝试通过在 SearchBar 中搜索在 Flatlist 中显示 Spoonacular API 的产品,运行代码时没有显示错误,但 Flatlist 只是保持空白,这是什么问题?
数据库文档链接:https://spoonacular.com/food-api/docs#Search-Grocery-Products
【问题讨论】:
-
如何在
SearchBar中调用updateSearch? -
您是否有成功的 GET 请求来实际填充您的状态?
-
在setState前放一个console,看数据是否正确获取:
console.log(res.data); -
示例对象没有
products键,所以这个<Text>{item.products.title}</Text>应该是<Text>{item.title}</Text>? -
在 render() 中尝试 console.log(data)
标签: javascript reactjs react-native axios react-native-flatlist