【问题标题】:FlatList stays blank after getting data from API从 API 获取数据后 FlatList 保持空白
【发布时间】: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键,所以这个&lt;Text&gt;{item.products.title}&lt;/Text&gt;应该是&lt;Text&gt;{item.title}&lt;/Text&gt;?
  • 在 render() 中尝试 console.log(data)

标签: javascript reactjs react-native axios react-native-flatlist


【解决方案1】:

响应数据形状为

{
    "products": [
        {
            "id": 192386,
            "title": "Pizza Buddy: Frozen Pizza Dough, 16 Oz",
            "imageType": "jpg"
        },
        {
            "id": 27693,
            "title": "Uno Pizza",
            "imageType": "jpg"
        }
    ],
    "totalProducts": 1258,
    "type": "product",
    "offset": 0,
    "number": 2
}

products 是应该传递给平面列表的数组。

<FlatList
  data={this.state.data.products} // <-- pass the products array from state
  renderItem={({ item }) => (
    <Text>{item.title}</Text> // <-- it is just item.title
  )}
  keyExtractor={item => item.id}
/>

这需要this.state.data 是一个对象,因此最好只使用products 数据更新状态。

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.products });
      })
      .catch((error) => {
        console.log(error.response.data);
      });
  } else {
    setState({ data: [] });
  }
}}

然后照常通过

<FlatList
  data={this.state.data}
  renderItem={({ item }) => (
    <Text>{item.title}</Text> // <-- it is just item.title
  )}
  keyExtractor={item => item.id}
/>

【讨论】:

  • 我试过你的例子,它给了我以下错误:undefined is not an object(evaluating 'this.state.data.products')
  • @PiersalvoMigliore 是的,我意识到在我离开后会发生这种情况。更新了我的答案,请再次检查。
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 2021-07-24
  • 2021-11-06
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多