【问题标题】:Set images state to Flickr API Response将图像状态设置为 Flickr API 响应
【发布时间】:2018-10-04 18:52:38
【问题描述】:

我正在开发 Flickr 克隆,其中发送 axios GET 请求以在用户输入输入时检索照片。 我当前的路径返回未定义。对象的响应数组在哪里,所以我知道在哪里设置图像状态?谢谢!

搜索容器

import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import axios from 'axios';
class Search extends Component {
  state = {
    searchText: '',
    images: []
  }

  onTextChange = (e) => {
    this.setState({searchText: e.target.value}, () => {
      axios.get('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ea72b9024308d54ba48382706bebb960&user_id=156981303%40N08&format=json&api_sig=f8866cedaa88ceccdfe1e1cf06dcaded')
      .then(response => {
        this.setState({images: response.???});
      })
      .catch(error => {
        console.log(error)
      });
    });
  }

  render() {
    console.log(this.state.images);
    return (
      <div>
        <TextField 
        name="searchText"
        value={this.state.searchText}
        onChange={this.onTextChange}
        floatingLabelText="Search for photos"
        fullWidth={true} 
        />
      </div>
    );
  }
}

export default Search;

【问题讨论】:

    标签: reactjs axios material-ui flickr


    【解决方案1】:

    尝试将您的 onTextChange 方法修改为:

    onTextChange = e => {
    this.setState({ searchText: e.target.value }, () => {
      axios
        .get(
          `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=ea72b9024308d54ba48382706bebb960&tags=${this.state.searchText}&tag_mode=any&format=json&nojsoncallback=1`
        )
        .then(response => response.data)
        .then(response => this.setState({ images: response.photos.photo }))
        .catch(error => {
          console.log(error);
        });
      });
    }
    

    【讨论】:

    • 感谢您的回复。我试过这个,它给了我一个错误。 TypeError:无法读取未定义的属性“照片”似乎对象数组不在“照片”中(因此未定义),因此无法读取“照片”。
    • 您的 user_id 或 api_sig 可能是错误的。最后一次编辑对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2019-10-28
    • 2021-04-24
    • 2012-11-25
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多