【问题标题】:Using this.setstate with Fetch API将 this.setstate 与 Fetch API 一起使用
【发布时间】:2021-01-03 06:23:37
【问题描述】:

我正在尝试使用 fetch 调用来检索一些 API 数据。不幸的是我不能用它来设置状态。

consructor() {
    this.state = {
      weather: ""
    };

  this.search = this.search.bind(this);
  }

  search(postalCode) {
    const url = `https://api.weatherbit.io/v2.0/forecast/daily?&postal_code=${postalCode}&key=${API_KEY}&days=7`;
    fetch(url)
     .then(response => response.json())
     .then(data => console.log(data));
  }'

此代码运行良好,并将包含正确数据的对象打印到控制台。

consructor() {
    this.state = {
      weather: ""
    };

  this.search = this.search.bind(this);
  }

  search(postalCode) {
    const url = `https://api.weatherbit.io/v2.0/forecast/daily?&postal_code=${postalCode}&key=${API_KEY}&days=7`; 
    fetch(url)
     .then(response => response.json())
     .then(data => this.setState({weather: data}))
     .catch(error => console.log(error));
  }

当我尝试使用数据更新我的状态时,我会收到“this.setState is not a function”错误。我已经在构造函数中绑定了搜索功能。

我什至试过这样绑定它:

fetch(url)
      .then(response => response.json())
      .then(data => this.setState({ weather: data })).bind(this);

这也不起作用。有人有什么想法吗?

【问题讨论】:

  • 只需将大括号括起来 { this.setState({your code}) } 就可以了
  • 你在constructor 中使用了super() 吗?如果没有,你必须

标签: reactjs fetch setstate


【解决方案1】:

我看不到你的类定义,但我相信使用状态需要你扩展组件

您遇到的问题是该组件中没有状态函数。

这是我的一个工作项目中使用类似提取的一些代码,由服务返回:


type HomeProps = {}

type State = {
    projects: ProjectModel[],
    skills: SkillModel[],
    resume: JobModel[]
}

export default class Home extends Component<HomeProps, State> {
    private projectService: ProjectService;

    constructor(props: HomeProps) {
        super(props);
        this.projectService = new ProjectService();

        this.state = {
            projects: []
        }
    }

    componentDidMount() {
        this.getProjects();
    }

    private getProjects() {
        this.projectService.retrieveItems().then(projects => {
            this.setState({projects});
        })
    }

这里是服务:

export default class ProjectService {

    url = "http://api.flynndev.us";

    async retrieveItems() {
        return fetch(`${this.url}/projects/all`)
            .then(response => response.json());
    }

    async getItem(itemLink: string) {
        return fetch(`${this.url}/projects/${itemLink}`)
            .then(response => response.json());
    }
}

注意:我正在使用 Typescript。随意忽略常规 React 的打字内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 2017-11-25
    • 2017-09-29
    • 1970-01-01
    • 2021-06-11
    • 2021-02-17
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多