【问题标题】:Get data from API with Search Bar使用搜索栏从 API 获取数据
【发布时间】:2021-03-25 21:18:00
【问题描述】:
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>

您好,我正在尝试使用 SearchBaraxios 从 Spoonacular API 获取数据,运行代码时出现以下错误:undefined is not a function (near '...this.state.data.map...')

数据库文档链接:https://spoonacular.com/food-api/docs#Search-Grocery-Products

【问题讨论】:

  • 看起来您实际上并没有在映射数据中使用迭代值。尝试将this.state.type.products.title 换成type.products.title
  • 谢谢你的回答,但是没有用

标签: reactjs react-native api search axios


【解决方案1】:

我认为您的问题是您正在尝试使用map with an empty data

将您的地图替换为FlatList

<FlatList
        data={this.state.data}
        renderItem={({ item }) => (
                  <Text>{item.products.title}</Text>
                ))}
        keyExtractor={item => item.id}
/>

【讨论】:

  • 感谢您的回答,错误将不再显示,但Flatlist 现在只是保持空白,没有显示任何内容
  • 这是正常的,因为您的状态“数据”是一个空数组 ( [ ] )。 flatlist 将在他的道具“数据”中循环,并使用“renderItem”中给出的函数渲染组件。答案中给出的代码可能是错误的,因为我不知道您要显示什么。通过在“数据”中给出一个固定值来尝试它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2021-03-12
  • 2020-09-03
  • 2013-12-03
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多