首页 > 解决方案 > Axios 不会在 Click 调用的函数中从 API 更新状态,但可以在 React 中的组件挂载上使用相同的函数

问题描述

我正在使用 Axios 在基本 React 组件中进行基本 API 拉取。当我的组件挂载时,我提取了一个随机 Chuck Norris 引用的 API,它运行良好。但是,当我尝试在名为 onClick 的相同函数中创建新的拉取和更新状态时,我收到一条错误消息,提示“未处理的拒绝 (TypeError):无法读取未定义的属性‘setState’。”

但是,当我 console.log 来自 API pull 的值时,它们给了我预期的结果,所以我不明白为什么我可以 console.log 一个值,获取一个字符串,然后让 React 告诉我这个字符串是未定义的。

我查看了几个 stackoverflow 线程,我看到的答案看起来与我当前的非工作解决方案相同。任何见解将不胜感激。

import React, {Component} from 'react'
import axios from 'axios'


class App extends Component {
  state = {
    quote: ''
  }

  componentDidMount(){
    axios.get('https://api.chucknorris.io/jokes/random')
      .then(res => {
        console.log('response', res.data.value)
        this.setState({
          quote: res.data.value
        })
      })
  }

  getNewFact(){
    axios.get('https://api.chucknorris.io/jokes/random')
      .then(res => {
        console.log('response', res.data.value)
        this.setState({
        quote: res.value
      })
    })
  }

  render () {
    return(
      <div>
      <h1>Chuck Norris Facts</h1>
      <p>{this.state.quote}</p>
    <button onClick={this.getNewFact}>get new fact</button>
    </div>
    )
  }
}

export default App

标签: reactjsapiaxios

解决方案


您必须使用箭头函数而不是普通函数,因为那this不是直接指向该类。所以而不是:

getNewFact(){
axios.get('https://api.chucknorris.io/jokes/random')
  .then(res => {
    console.log('response', res.data.value)
    this.setState({
    quote: res.value
  })
})

}

将会:

getNewFact = () => {
axios.get('https://api.chucknorris.io/jokes/random')
  .then(res => {
    console.log('response', res.data.value)
    this.setState({
    quote: res.data.value // also fix this or nothing will show after clicking the button
  })
})

}


推荐阅读